diff --git a/policies/put_cups/gpt61terra-s2/policy.py b/policies/put_cups/gpt61terra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b0d0033f43cbb9a891555f01dd6f2f4212be9e21 --- /dev/null +++ b/policies/put_cups/gpt61terra-s2/policy.py @@ -0,0 +1,62 @@ +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[19:21] = 0 + if t < 110: + a[0] = -.3 + if t >= 110: + a[8] = a[15] = 1.5 + if t >= 180: + a[5] = a[12] = -1.5 + if t >= 260: + a[8] = a[15] = 0 + if t >= 340: + a[5] = a[12] = -.6 + if 420 <= t < 620: + a[0] = .2 + if 620 <= t < 680: + a[1] = .15 + if 760 <= t < 1390: + a[5] = a[12] = -1. + a[7], a[14] = -.1, .5 + if 840 <= t < 940: + a[0] = .15 + if 1000 <= t < 1320: + a[19:21] = 1 + if 1070 <= t < 1270: + a[0], a[1] = -.08, .16 + if t >= 1390: + a[5], a[12] = -.6, -.9 + a[7], a[14] = .15, .50 + a[4] = .25 + a[10], a[17] = .15, .2 + if 1390 <= t < 1950: + x, y, _, yaw = obs['low_dim_obs'][21:25] + dx, dy = .25 - x, .03 - y + vx, vy = np.clip(1.2*dx, -.18, .18), np.clip(1.2*dy, -.18, .18) + speed = np.hypot(vx, vy) + if speed < .018: + vx = vy = 0. + elif speed < .08: + vx *= .08 / speed + vy *= .08 / speed + a[0] = np.cos(yaw)*vx + np.sin(yaw)*vy + a[1] = -np.sin(yaw)*vx + np.cos(yaw)*vy + a[3] = np.clip(1.2*(-.2-yaw), -.3, .3) + if 2050 <= t < 2650: + a[19:21] = 1 + if t >= 2150: + a[5] = a[12] = -2.0 + a[8] = a[15] = 1.1 + a[10] = a[17] = .45 + if 2340 <= t < 2440: + a[0] = .1 + if t >= 2650: + a[19:21] = 0 + return a diff --git a/policies/put_cups/gpt61terra-s3/episodes.csv b/policies/put_cups/gpt61terra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f07188c1e36ce62841ee9aa30874cd299fb4de7e --- /dev/null +++ b/policies/put_cups/gpt61terra-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/gpt61terra-s3/policy.py b/policies/put_cups/gpt61terra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..94557d38e19530d64d367a69a495fe7e312feab5 --- /dev/null +++ b/policies/put_cups/gpt61terra-s3/policy.py @@ -0,0 +1,40 @@ +"""Deterministic coordinated reach for the counter and wall cabinet.""" +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 + # Each pose is (duration, torso pitch, shoulder pitch, shoulder roll, + # shoulder yaw, elbow, wrist pitch, grip). + self.poses = [ + (100, 0., -.50, 0., 0., 0., 0., 0.), + (100, 0., -1.05, 0., 0., 0., 0., 0.), + (100, .18, -1.20, 0., 0., 0., 0., 0.), + (60, .18, -1.20, 0., 0., 0., 0., 1.), + (130, 0., -.95, .35, 0., 0., 0., 1.), + (60, 0., -.95, .35, 0., 0., 0., 0.), + (100, 0., -.55, .15, 0., 0., 0., 0.), + (100, .20, -.70, .05, 0., 0., 0., 0.), + (100, .35, -.85, .05, 0., 0., 0., 0.), + (80, .35, -.85, .05, 0., 0., 0., 1.), + (150, .18, -1.40, .05, 0., 0., 0., 1.), + (100, .35, -1.50, .05, 0., 0., 0., 1.), + (80, .35, -1.50, .05, 0., 0., 0., 0.), + (100, 0., -1.0, .1, 0., 0., 0., 0.), + ] + self.targets=[] + for duration,p,sp,sr,sy,e,wp,g in self.poses: + a=self.initial.copy();a[4]=p + a[5:12]=[sp,sr,sy,e,0,wp,0] + a[12:19]=[sp,-sr,-sy,e,0,wp,0] + a[19:21]=g + self.targets.append(a) + def act(self, obs, tools): + t=int(obs['t']); start=self.initial + for (duration,*_),target in zip(self.poses,self.targets): + if t < duration: + f=min(1.,t/max(1,min(duration,70))) + return start*(1-f)+target*f + t-=duration;start=target + return start diff --git a/policies/put_cups/gpt6sol-s1/episodes.csv b/policies/put_cups/gpt6sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f07188c1e36ce62841ee9aa30874cd299fb4de7e --- /dev/null +++ b/policies/put_cups/gpt6sol-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/gpt6sol-s1/policy.py b/policies/put_cups/gpt6sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..23be426b0448612e869f26f9f8a9ebbb4670d613 --- /dev/null +++ b/policies/put_cups/gpt6sol-s1/policy.py @@ -0,0 +1,97 @@ +"""Deterministic camera and proprioception based cup stowing controller.""" + +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.a[:5] = [0, 0, 0.74, 0, 0] + self.a[19:21] = 0 + self.stages = [] + self.index = 0 + self.tick = 0 + self.start = self.a.copy() + self._build() + + def pose(self, n, changes): + self.stages.append(("pose", n, changes)) + + def walk(self, x, y, n=150): + self.stages.append(("walk", n, (x, y))) + + def hold(self, n): + self.stages.append(("hold", n, None)) + + def _build(self): + # Reach the two wall cabinet handles and pull the doors outward. + self.pose(55, {5: -.5, 12: -.5, 8: -.8, 15: -.8}) + self.walk(.42, 0, 145) + self.hold(20) + self.pose(35, {19: 1, 20: 1}) + self.pose(75, {8: -.2}) + self.pose(35, {15: -.2}) + self.pose(30, {19: 0, 20: 0}) + self.pose(45, {5: -.35, 12: -.35, 8: 0, 15: 0}) + + # Retreat with each cup before lifting it past the counter. + for side, cup_y in (("left", -.10), ("right", .15)): + p = 5 if side == "left" else 12 + e = 8 if side == "left" else 15 + w = 10 if side == "left" else 17 + g = 19 if side == "left" else 20 + self.walk(.30, cup_y, 180) + self.hold(25) + self.pose(40, {g: 1}) + self.pose(55, {p: -.7}) + self.walk(.08, cup_y, 130) + self.pose(75, {p: -1.1}) + self.pose(75, {e: -.6}) + self.walk(.08, 0, 100) + self.walk(.40, 0, 180) + self.pose(70, {p: -.8}) + self.pose(45, {g: 0}) + self.pose(70, {w: -.5}) + self.walk(.10, 0, 145) + self.pose(55, {p: -.35, e: 0, w: 0}) + + def act(self, obs, tools): + if self.index >= len(self.stages): + out = self.a.copy() + out[0] = out[1] = out[3] = 0 + return out + + kind, duration, target = self.stages[self.index] + out = self.a.copy() + out[0] = out[1] = out[3] = 0 + if kind == "pose": + fraction = min(1.0, (self.tick + 1) / duration) + for j, value in target.items(): + out[j] = self.start[j] + (value - self.start[j]) * fraction + complete = self.tick + 1 >= duration + elif kind == "walk": + state = obs["low_dim_obs"] + x, y, yaw = float(state[21]), float(state[22]), float(state[24]) + dx, dy = target[0] - x, target[1] - y + c, s = np.cos(yaw), np.sin(yaw) + forward, lateral = c * dx + s * dy, -s * dx + c * dy + if abs(dx) > .018 or abs(dy) > .018: + if abs(forward) > .012: + out[0] = np.sign(forward) * min(.16, max(.085, abs(forward) * 1.3)) + if abs(lateral) > .012: + out[1] = np.sign(lateral) * min(.16, max(.085, abs(lateral) * 1.3)) + if abs(yaw) > .045: + out[3] = np.clip(-1.5 * yaw, -.22, .22) + complete = (self.tick > 25 and abs(dx) < .027 and abs(dy) < .027 + and abs(yaw) < .07) or self.tick + 1 >= duration + else: + complete = self.tick + 1 >= duration + + self.a = out + if complete: + self.index += 1 + self.tick = 0 + self.start = self.a.copy() + else: + self.tick += 1 + return out diff --git a/policies/put_cups/gpt6sol-s2/episodes.csv b/policies/put_cups/gpt6sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f07188c1e36ce62841ee9aa30874cd299fb4de7e --- /dev/null +++ b/policies/put_cups/gpt6sol-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/gpt6sol-s2/policy.py b/policies/put_cups/gpt6sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..dc6a7e95cd16e488b091c55d3ee1ba58627e90bc --- /dev/null +++ b/policies/put_cups/gpt6sol-s2/policy.py @@ -0,0 +1,159 @@ +"""Deterministic upper-body and base control for the cabinet task.""" + +import math +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = 0 + self.age = 0 + self.retried = {"left": False, "right": False} + self.stages = [ + ("door_pose", 80), ("door_walk", 35), ("door_aim", 50), + ("door_push", 60), ("door_settle", 15), ("door_grip", 65), + ("door_swing", 80), ("door_release", 50), ("arms_rest", 70), + ("center", 300), + ("left_pose", 70), ("left_walk", 60), ("left_stop", 20), + ("left_approach", 80), ("left_push", 55), ("left_settle", 15), + ("left_grip", 65), ("left_lift", 75), ("left_high", 110), + ("left_lean", 85), ("left_release", 75), ("left_rest", 70), + ("center", 240), + ("right_pose", 70), ("right_walk", 60), ("right_stop", 20), + ("right_approach", 80), ("right_push", 55), ("right_settle", 15), + ("right_grip", 65), ("right_lift", 75), ("right_high", 110), + ("right_lean", 85), ("right_release", 75), ("right_rest", 80), + ("finish", 10000), + ] + + def _start(self, name): + a = self.a + a[0] = a[1] = a[3] = 0 + if name == "door_pose": + a[2] = .74 + a[4] = 0 + a[5:12] = [-1.1, 0, -.2, 0, 0, -.2, 0] + a[12:19] = [-1.1, 0, .2, 0, 0, -.2, 0] + a[19:21] = 0 + elif name == "door_aim": + a[10] = a[17] = .2 + elif name == "door_grip": + a[19:21] = 1 + elif name == "door_swing": + a[7], a[14] = .7, -.7 + elif name == "door_release": + a[19:21] = 0 + elif name == "arms_rest": + a[5:19] = 0 + elif name == "left_pose": + a[4] = 0 + a[5:12] = [-.5, 0, .2, 0, 0, 0, 0] + a[19] = 0 + elif name == "left_approach": + a[4], a[5], a[10] = .2, -.7, .4 + elif name in ("left_grip", "left_retry_grip"): + a[19] = 1 + elif name == "left_retry_open": + a[19] = 0 + elif name == "left_retry_aim": + a[7] = .1 + elif name == "left_lift": + a[4], a[5], a[10] = 0, -.9, .6 + elif name == "left_high": + a[5], a[10] = -1.5, 1.2 + elif name == "left_lean": + a[4] = .4 + elif name == "left_release": + a[19] = 0 + elif name == "left_rest": + a[4] = 0 + a[5:12] = 0 + elif name == "right_pose": + a[4] = 0 + a[12:19] = [-.5, 0, .2, 0, 0, 0, 0] + a[20] = 0 + elif name == "right_approach": + a[4], a[12], a[17] = .3, -.8, .4 + elif name in ("right_grip", "right_retry_grip"): + a[20] = 1 + elif name == "right_retry_open": + a[20] = 0 + elif name == "right_retry_aim": + a[14] = .1 + elif name == "right_lift": + a[4], a[12], a[17] = 0, -.9, .6 + elif name == "right_high": + a[12], a[17] = -1.5, 1.2 + elif name == "right_lean": + a[4] = .4 + elif name == "right_release": + a[20] = 0 + elif name == "right_rest": + a[4] = 0 + a[12:19] = 0 + + @staticmethod + def _small_velocity(cmd, error): + if abs(error) <= .012: + return 0.0 + if abs(cmd) < .08: + return .08 if error > 0 else -.08 + return float(cmd) + + def _base(self, name, low): + a = self.a + x, y, _, yaw = (float(v) for v in low[21:25]) + a[0] = a[1] = a[3] = 0 + if name == "door_walk": + a[0] = .15 + elif name == "door_push": + a[0] = .12 + elif name in ("left_walk", "right_walk"): + a[0] = .1 + elif name in ("left_push", "right_push"): + a[0] = .12 + if name == "center": + dx, dy = .168 - x, -.003 - y + forward = math.cos(yaw) * dx + math.sin(yaw) * dy + lateral = -math.sin(yaw) * dx + math.cos(yaw) * dy + a[0] = float(np.clip(1.5 * forward, -.25, .25)) + if abs(a[0]) < .06: + a[0] = 0 + a[1] = self._small_velocity(np.clip(1.5 * lateral, -.2, .2), dy) + a[3] = float(np.clip(-2 * yaw, -.5, .5)) + if abs(yaw) < .015: + a[3] = 0 + elif name in ("left_pose", "left_walk", "left_stop", "left_approach", + "left_push", "left_settle", "left_retry_open", "left_retry_aim"): + ey, ew = .015 - y, .008 - yaw + a[1] = self._small_velocity(np.clip(2 * ey, -.12, .12), ey) + a[3] = float(np.clip(2 * ew, -.3, .3)) if abs(ew) >= .01 else 0 + elif name in ("right_pose", "right_walk", "right_stop", "right_approach", + "right_push", "right_settle", "right_retry_open", "right_retry_aim"): + ey, ew = -.02 - y, -.02 - yaw + a[1] = self._small_velocity(np.clip(2 * ey, -.12, .12), ey) + a[3] = float(np.clip(2 * ew, -.3, .3)) if abs(ew) >= .01 else 0 + if name in ("left_lean", "right_lean") and x < .22: + a[0] = .08 + + def act(self, obs, tools): + name, length = self.stages[min(self.phase, len(self.stages) - 1)] + if self.age == 0: + self._start(name) + self._base(name, obs["low_dim_obs"]) + action = self.a.copy() + self.age += 1 + if self.age >= length: + low = obs["low_dim_obs"] + if name == "left_grip" and not self.retried["left"] and max(low[10], low[11]) < -.018: + self.stages[self.phase + 1:self.phase + 1] = [ + ("left_retry_open", 35), ("left_retry_aim", 55), ("left_retry_grip", 65)] + self.retried["left"] = True + if name == "right_grip" and not self.retried["right"] and max(low[19], low[20]) < -.018: + self.stages[self.phase + 1:self.phase + 1] = [ + ("right_retry_open", 35), ("right_retry_aim", 55), ("right_retry_grip", 65)] + self.retried["right"] = True + self.phase += 1 + self.age = 0 + return action diff --git a/policies/put_cups/gpt6sol-s3/episodes.csv b/policies/put_cups/gpt6sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f07188c1e36ce62841ee9aa30874cd299fb4de7e --- /dev/null +++ b/policies/put_cups/gpt6sol-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/gpt6sol-s3/policy.py b/policies/put_cups/gpt6sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d5ccba9fec92c21951e5dd405ec0a83a6ca226b1 --- /dev/null +++ b/policies/put_cups/gpt6sol-s3/policy.py @@ -0,0 +1,154 @@ +"""Deterministic camera-guided cup handling policy.""" + +import cv2 +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.a[[0, 1, 3]] = 0 + self.stage = 0 + self.k = 0 + self.start = self.a.copy() + self.yaws = np.array([-.25, .4], dtype=float) + self.pitches = np.array([-.3, -.3], dtype=float) + self.saved_pitches = self.pitches.copy() + + def next_stage(self): + self.stage += 1 + self.k = 0 + self.start = self.a.copy() + + def move(self, target, duration): + u = min(1.0, (self.k + 1) / duration) + self.a[:] = self.start + u * (target - self.start) + if self.k + 1 >= duration: + self.next_stage() + + @staticmethod + def find_cup(image): + rgb = image.astype(np.int16) + spread = rgb.max(2) - rgb.min(2) + mask = ((rgb[:, :, 0] > 112) & (rgb[:, :, 1] > 112) + & (rgb[:, :, 2] > 112) & (spread < 38)).astype(np.uint8) + mask[:5] = 0 + count, _, boxes, centers = cv2.connectedComponentsWithStats(mask) + best = None + for i in range(1, count): + x, y, w, h, area = boxes[i] + if area < 65 or w < 7 or h < 12 or y > 72: + continue + cost = abs(centers[i, 0] - 42) + .15 * abs(centers[i, 1] - 45) + if best is None or cost < best[0]: + best = (cost, centers[i]) + return None if best is None else best[1] + + def act(self, obs, tools): + s, k = self.stage, self.k + z = obs["low_dim_obs"] + self.a[[0, 1, 3]] = 0 + + if s == 0: + b = self.start.copy() + b[5] = b[12] = -1.2 + b[19:21] = .6 + self.move(b, 120) + elif s == 1: + self.a[0] = .2 if z[21] < .245 and k < 90 else 0 + if z[21] >= .245 or k >= 90: + self.next_stage() + elif s == 2: + if k >= 49: + self.next_stage() + elif s == 3: + b = self.start.copy() + b[2], b[4] = .74, .5 + b[5] = b[12] = -.6 + b[7], b[14] = -.25, .4 + b[10] = b[17] = -.3 + b[19:21] = .6 + self.move(b, 180) + if self.stage == 4: + self.yaws[:] = self.a[[7, 14]] + self.pitches[:] = self.a[[10, 17]] + elif s == 4: + u = min(1.0, (k + 1) / 180) + self.a[5] = self.a[12] = -.6 - .45 * u + self.a[2] = .74 - .10 * u + self.a[4] = .5 + .2 * u + self.a[0] = .2 if k < 100 and z[21] < .255 else 0 + if k % 5 == 0: + for side, cam in enumerate(("left_wrist", "right_wrist")): + xy = self.find_cup(tools.image(cam)) + if xy is None: + continue + self.yaws[side] = np.clip(self.yaws[side] + .0025 * (42 - xy[0]), -.8, .8) + self.pitches[side] = np.clip(self.pitches[side] + .0025 * (xy[1] - 45), -.8, .8) + self.a[7], self.a[14] = self.yaws + self.a[10], self.a[17] = self.pitches + if k >= 179: + self.saved_pitches[:] = self.pitches + self.next_stage() + elif s == 5: + self.a[19:21] = .6 + .4 * min(1.0, (k + 1) / 80) + if k >= 79: + self.next_stage() + elif s == 6: + b = self.start.copy() + b[2], b[4] = .74, .5 + b[5] = b[12] = -1.3 + b[10] = np.clip(self.saved_pitches[0] + .25, -1.5, 1.5) + b[17] = np.clip(self.saved_pitches[1] + .25, -1.5, 1.5) + self.move(b, 150) + elif s == 7: + self.a[0] = .2 if z[21] < .28 and k < 80 else 0 + if z[21] >= .28 or k >= 80: + self.next_stage() + elif s == 8: + b = self.start.copy() + b[2], b[4] = .84, .4 + b[5] = b[12] = -2.0 + b[10] = np.clip(self.saved_pitches[0] + .9, -1.5, 1.5) + b[17] = np.clip(self.saved_pitches[1] + .9, -1.5, 1.5) + self.move(b, 80) + elif s == 9: + self.a[19:21] = 1.0 + if k >= 99: + self.next_stage() + elif s == 10: + b = self.start.copy() + b[2], b[4] = .74, 0 + b[5] = b[12] = -.7 + b[19:21] = .6 + self.move(b, 150) + elif s == 11: + b = self.start.copy() + b[2], b[4] = .56, .6 + b[5] = b[12] = -1.1 + b[7], b[14] = -.4, .4 + b[10] = b[17] = .2 + b[19:21] = .6 + self.move(b, 170) + elif s == 12: + self.a[19:21] = .6 + .4 * min(1.0, (k + 1) / 80) + if k >= 79: + self.next_stage() + elif s == 13: + b = self.start.copy() + b[2] = .74 + b[5] = b[12] = -1.3 + b[10] = b[17] = .4 + self.move(b, 150) + elif s == 14: + b = self.start.copy() + b[2], b[4] = .84, .4 + b[5] = b[12] = -2.0 + b[10] = b[17] = 1.0 + self.move(b, 80) + elif s == 15: + self.a[19:21] = 1.0 + if k >= 99: + self.next_stage() + self.k += 1 + return self.a.copy() diff --git a/policies/put_cups/kimi31pro-s1/episodes.csv b/policies/put_cups/kimi31pro-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f07188c1e36ce62841ee9aa30874cd299fb4de7e --- /dev/null +++ b/policies/put_cups/kimi31pro-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/kimi31pro-s1/policy.py b/policies/put_cups/kimi31pro-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..9dedfab261f1fbdf7676eb7d85d0ea14387f56c1 --- /dev/null +++ b/policies/put_cups/kimi31pro-s1/policy.py @@ -0,0 +1,160 @@ +"""Deterministic, hand-written controller for the two-cup cabinet task.""" + +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.raw = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.raw[[0, 1, 3]] = 0.0 + planned = self.raw.copy() + self.ops = [] + + def move(n, left=None, right=None, grips=None, height=None, pitch=None): + nonlocal planned + planned = planned.copy() + planned[[0, 1, 3]] = 0.0 + if left is not None: + planned[5:12] = left + if right is not None: + planned[12:19] = right + if grips is not None: + planned[19:21] = grips + if height is not None: + planned[2] = height + if pitch is not None: + planned[4] = pitch + self.ops.append(("move", int(n), planned.copy())) + + def go(n, x): + self.ops.append(("go", int(n), float(x))) + + def velocity(n, vx): + self.ops.append(("velocity", int(n), float(vx))) + + def hold(n): + self.ops.append(("hold", int(n), None)) + + # Open both wall-cabinet doors. + move(46, [-1, 0, 0, 0, 0, 0, 0], [-1, 0, 0, 0, 0, 0, 0], [0, 0], pitch=0) + go(59, .25) + move(17, grips=[.6, .6]) + move(23, grips=[1, 1]) + velocity(59, -.20) + move(17, grips=[0, 0]) + + # Pick up the left cup with a gentle, partially closed grip. + move(39, [-.4, .3, 0, 0, 0, 0, 0], [-1, 0, 0, 0, 0, 0, 0]) + go(72, .32) + move(30, [-.3, .55, 0, 0, -.6, 0, 0]) + velocity(25, .08) + hold(10) + move(23, [-.3, .65, 0, 0, -.6, 0, 0]) + move(36, height=.675) + move(23, grips=[.8, 0]) + move(59, height=.74) + + # Carry through the door opening, then release at shelf level. + move(78, [-1, 0, 0, 0, 0, 0, 0], [-.75, 0, 0, 0, 0, 0, 0]) + go(65, .45) + move(46, [-.75, 0, 0, 0, 0, 0, 0]) + hold(20) + move(20, grips=[0, 0]) + hold(33) + + # Pick up the remaining cup with the right arm. Shoulder yaw avoids + # the counter contact caused by using the left arm's roll trajectory. + move(39, [-1, 0, 0, 0, 0, 0, 0], [-.4, 0, 0, 0, 0, -.6, 0]) + go(72, .32) + move(30, right=[-.3, 0, .4, 0, -.6, 0, 0]) + velocity(25, .08) + hold(10) + move(36, height=.675) + move(23, grips=[0, .8]) + move(59, height=.74) + move(78, right=[-1, 0, 0, 0, 0, 0, 0]) + go(65, .45) + move(46, right=[-.75, 0, 0, 0, 0, 0, 0]) + hold(20) + move(20, grips=[0, 0]) + hold(70) + + # Bounded recovery attempts, used only when the first cycle did not + # satisfy the task. A slightly closer approach covers a shallow miss. + move(39, [-.4, .3, 0, 0, 0, 0, 0], [-1, 0, 0, 0, 0, 0, 0]) + go(72, .36) + move(30, [-.3, .55, 0, 0, -.6, 0, 0]) + velocity(25, .08) + hold(10) + move(23, [-.3, .65, 0, 0, -.6, 0, 0]) + move(36, height=.675) + move(23, grips=[.8, 0]) + move(59, height=.74) + move(78, [-1, 0, 0, 0, 0, 0, 0], [-.75, 0, 0, 0, 0, 0, 0]) + go(65, .45) + move(46, [-.75, 0, 0, 0, 0, 0, 0]) + hold(20) + move(20, grips=[0, 0]) + hold(33) + + move(39, [-1, 0, 0, 0, 0, 0, 0], [-.4, 0, 0, 0, 0, -.6, 0]) + go(72, .36) + move(30, right=[-.3, 0, .4, 0, -.6, 0, 0]) + velocity(25, .08) + hold(10) + move(36, height=.675) + move(23, grips=[0, .8]) + move(59, height=.74) + move(78, right=[-1, 0, 0, 0, 0, 0, 0]) + go(65, .45) + move(46, right=[-.75, 0, 0, 0, 0, 0, 0]) + hold(20) + move(20, grips=[0, 0]) + hold(100) + + self.phase = 0 + self.phase_t = 0 + self.start = self.raw.copy() + + def _advance(self): + self.phase += 1 + self.phase_t = 0 + self.start = self.raw.copy() + + def act(self, obs, tools): + if self.phase >= len(self.ops): + raw = self.raw.copy() + raw[[0, 1, 3]] = 0.0 + return raw + + kind, duration, data = self.ops[self.phase] + if kind == "move": + if self.phase_t == 0: + self.start = self.raw.copy() + u = float(self.phase_t + 1) / duration + u = u * u * (3.0 - 2.0 * u) + self.raw = (1.0 - u) * self.start + u * data + elif kind == "go": + p = obs["low_dim_obs"] + ex = data - float(p[21]) + ey = -float(p[22]) + dy = (-float(p[24]) + np.pi) % (2.0 * np.pi) - np.pi + self.raw[[0, 1, 3]] = 0.0 + if abs(ex) > .006 or abs(float(p[46])) > .025: + self.raw[0] = np.clip(2.5 * ex - .6 * float(p[46]), -.18, .18) + if abs(ey) > .008: + self.raw[1] = np.clip(2.5 * ey, -.1, .1) + if abs(dy) > .015: + self.raw[3] = np.clip(2.0 * dy, -.15, .15) + elif kind == "velocity": + self.raw[[0, 1, 3]] = 0.0 + self.raw[0] = data + else: + self.raw[[0, 1, 3]] = 0.0 + + self.phase_t += 1 + if self.phase_t >= duration: + if kind == "velocity": + self.raw[0] = 0.0 + self._advance() + return np.asarray(self.raw, dtype=np.float32) diff --git a/policies/put_cups/kimi31pro-s2/episodes.csv b/policies/put_cups/kimi31pro-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f07188c1e36ce62841ee9aa30874cd299fb4de7e --- /dev/null +++ b/policies/put_cups/kimi31pro-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/kimi31pro-s2/policy.py b/policies/put_cups/kimi31pro-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..cbe964a084e39070aada8bd67a59b716127704a7 --- /dev/null +++ b/policies/put_cups/kimi31pro-s2/policy.py @@ -0,0 +1,221 @@ +"""Deterministic, hand-written controller for the cup-storage task. + +The controller uses joint-space arm trajectories, a pelvis-position servo, and +finger contact feedback. It does not use learned models or stored observations. +""" + +import numpy as np + + +Z = np.zeros(7, dtype=float) + + +def wrap(a): + return (a + np.pi) % (2 * np.pi) - np.pi + + +class Policy: + def reset(self, obs, tools): + hold = np.asarray(tools.hold_action(), dtype=float) + self.left = hold[5:12].copy() + self.right = hold[12:19].copy() + self.lg = float(hold[19]) + self.rg = float(hold[20]) + self.height = float(hold[2]) + self.pitch = float(hold[4]) + p = obs["low_dim_obs"] + self.home = np.array([p[21], p[22], p[24]], dtype=float) + self.anchor = self.home.copy() + self.post_door = self.home.copy() + self.current = None + self.ops = [] + self.i = 0 + self.place_i = 0 + self.cup_index = 0 + self.final = False + self.stage_t = 0 + self._door_ops() + + @staticmethod + def op(left, right, lg, rg, n, pitch=0.0, height=0.74, + anchor=None, velocity=None, kind="move"): + return { + "left": np.asarray(left, dtype=float).copy(), + "right": np.asarray(right, dtype=float).copy(), + "lg": float(lg), "rg": float(rg), "n": int(n), + "pitch": float(pitch), "height": float(height), + "anchor": None if anchor is None else np.asarray(anchor, dtype=float).copy(), + "velocity": velocity, "kind": kind, + } + + def _door_ops(self): + a = np.array([-0.8, 0, 0, 0, 0, 0, 0]) + b = np.array([-1.3, 0, 0, 0, 0, 0, 0]) + h = np.array([-1.3, 0, 0, 0.4, 0, 0, 0]) + self.ops = [ + self.op(Z, a, 0, 0, 40, anchor=self.home), + self.op(Z, b, 0, 0, 40, anchor=self.home), + self.op(Z, h, 0, 0, 40, anchor=self.home), + self.op(Z, h, 0, 0, 40, anchor=self.home), + self.op(Z, h, 0, 1, 50, anchor=self.home), + self.op(Z, h, 0, 1, 100, velocity=(-0.18, -0.18)), + self.op(Z, h, 0, 0, 30), + self.op(Z, a, 0, 0, 50, kind="door_done"), + ] + self.i = 0 + + def _cup_ops(self): + """Build one collision-free approach, contact search, and placement.""" + k = self.cup_index + # Stay on the open-door side while approaching the first cup. Later + # cups are reached by moving left along the counter. + grasp_home = np.array([ + self.home[0], self.post_door[1] + 0.20 * k, self.post_door[2] + ]) + place_home = np.array([ + self.home[0], self.post_door[1] + 0.05 * k, self.post_door[2] + ]) + retreat = np.array([-0.8, 0, 0, 0, 0, 0, 0]) + extend = np.array([-1.3, 0, 0, 0, 0, 0, 0]) + pre = np.array([-1.3, 0, 0, 0.7, 0, 0, 0]) + grasp = np.array([-1.3, 0, 0, 1.2, 0, 0, 0]) + lift = np.array([-1.55, 0, 0, 1.45, 0, 0, 0]) + shelf = np.array([-1.3, 0, 0, 0.1, 0, 0, 0]) + ops = [ + self.op(Z, retreat, 0, 0, 30, anchor=grasp_home), + self.op(Z, extend, 0, 0, 45, anchor=grasp_home), + self.op(Z, pre, 0, 0, 30, anchor=grasp_home), + ] + offsets = [-0.10, -0.06, -0.03, 0.03] if k < 2 else [-0.10, -0.03] + for j, dx in enumerate(offsets): + target = grasp_home.copy() + target[0] += dx + ops.append(self.op(Z, grasp, 0, 0, 45, pitch=0.2, + anchor=target)) + ops.append(self.op(Z, grasp, 0, 1, 35, pitch=0.2, + anchor=target)) + ops.append(self.op(Z, grasp, 0, 0, 5, pitch=0.2, + anchor=target)) + ops.append(self.op(Z, lift, 0, 1, 55, pitch=0.2, + anchor=target, kind="candidate_lift")) + self.place_i = len(ops) + ops.append(self.op(Z, shelf, 0, 1, 70, pitch=0.35, + anchor=place_home, kind="place")) + ops.append(self.op(Z, shelf, 0, 0, 40, pitch=0.35, + anchor=place_home, kind="cup_release")) + self.ops = ops + self.i = 0 + + def _final_ops(self): + shelf = np.array([-1.3, 0, 0, 0.1, 0, 0, 0]) + self.final = True + self.ops = [self.op(Z, shelf, 0, 0, 50, pitch=0.35, + anchor=self.anchor, kind="final")] + self.i = 0 + + def _after_cup(self): + if self.cup_index < 3: + self.cup_index += 1 + self._cup_ops() + else: + self._final_ops() + + def _start(self): + self.current = self.ops[self.i] + self.i += 1 + self.stage_t = 0 + op = self.current + self.start_left = self.left.copy() + self.start_right = self.right.copy() + self.start_pitch = self.pitch + self.start_height = self.height + if op["anchor"] is not None: + self.anchor = op["anchor"].copy() + + def _finish(self, obs): + op = self.current + self.left = op["left"].copy() + self.right = op["right"].copy() + self.lg = op["lg"] + self.rg = op["rg"] + self.pitch = op["pitch"] + self.height = op["height"] + if op["velocity"] is not None: + p = obs["low_dim_obs"] + self.anchor = np.array([p[21], p[22], p[24]], dtype=float) + kind = op["kind"] + self.current = None + if kind == "door_done": + p = obs["low_dim_obs"] + self.post_door = np.array([p[21], p[22], p[24]], dtype=float) + self.cup_index = 0 + self._cup_ops() + elif kind == "candidate_lift": + held = bool(obs["low_dim_obs"][51] < 0.95) + if held: + self.i = self.place_i + elif self.i >= self.place_i: + self._after_cup() + elif kind == "cup_release": + self._after_cup() + elif kind == "final": + self.ops = [] + self.i = 0 + + def _base_action(self, obs, op): + p = obs["low_dim_obs"] + yaw = float(p[24]) + if op["velocity"] is not None: + vx, vy = op["velocity"] + eyaw = wrap(self.anchor[2] - yaw) + wz = np.clip(1.2 * eyaw, -0.4, 0.4) + return vx, vy, wz + ex, ey = self.anchor[:2] - np.array([p[21], p[22]]) + vxw = np.clip(2.2 * ex, -0.20, 0.20) if abs(ex) > 0.012 else 0.0 + vyw = np.clip(2.2 * ey, -0.20, 0.20) if abs(ey) > 0.012 else 0.0 + c, s = np.cos(yaw), np.sin(yaw) + vx = c * vxw + s * vyw + vy = -s * vxw + c * vyw + speed = float(np.hypot(vx, vy)) + if 0.0 < speed < 0.06: + vx *= 0.06 / speed + vy *= 0.06 / speed + eyaw = wrap(self.anchor[2] - yaw) + wz = np.clip(1.4 * eyaw, -0.35, 0.35) if abs(eyaw) > 0.02 else 0.0 + return vx, vy, wz + + def act(self, obs, tools): + if not self.ops and self.current is None: + a = np.zeros(21, dtype=float) + a[2] = self.height + a[4] = self.pitch + a[5:12] = self.left + a[12:19] = self.right + a[19] = self.lg + a[20] = self.rg + return a + if self.current is None: + if self.i >= len(self.ops): + if not self.final: + self._after_cup() + else: + self.ops = [] + return self.act(obs, tools) + self._start() + op = self.current + u = min(1.0, (self.stage_t + 1) / 30.0) + left = self.start_left * (1.0 - u) + op["left"] * u + right = self.start_right * (1.0 - u) + op["right"] * u + pitch = self.start_pitch * (1.0 - u) + op["pitch"] * u + height = self.start_height * (1.0 - u) + op["height"] * u + vx, vy, wz = self._base_action(obs, op) + a = np.zeros(21, dtype=float) + a[:5] = [vx, vy, height, wz, pitch] + a[5:12] = left + a[12:19] = right + a[19] = op["lg"] + a[20] = op["rg"] + self.stage_t += 1 + if self.stage_t >= op["n"]: + self._finish(obs) + return a diff --git a/policies/put_cups/opus-s1/episodes.csv b/policies/put_cups/opus-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..044c22cf50eda8adceb6875eb8f9f882c76cab95 --- /dev/null +++ b/policies/put_cups/opus-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,1,2592,success,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,1,2659,success,0 +620026,0,3000,timeout,0 +620027,0,3000,timeout,0 +620028,0,3000,timeout,0 +620029,0,3000,timeout,0 +620030,1,2593,success,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,1,2635,success,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,2512,success,0 +620050,1,2576,success,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,1,2570,success,0 +620063,0,3000,timeout,0 +620064,0,3000,timeout,0 +620065,0,3000,timeout,0 +620066,0,3000,timeout,0 +620067,1,2545,success,0 +620068,1,2553,success,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,1,2634,success,0 +620079,1,2409,success,0 +620080,1,2581,success,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,1,2529,success,0 +620092,0,3000,timeout,0 +620093,1,2600,success,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/opus-s1/policy.py b/policies/put_cups/opus-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..74004cc0080fa818f915ecb4a3ef395ce0658138 --- /dev/null +++ b/policies/put_cups/opus-s1/policy.py @@ -0,0 +1,685 @@ +"""Put the cups from the counter into the wall cabinet (Unitree G1, scripted). + +Sequence (all hand-written control): + 1. open the right and the left cabinet door: grasp the vertical bar handle and + swing it around the hinge, + 2. look at the counter with both wrist cameras and locate the cups and their + handles (calibrated pinhole model of the wrist cameras + arm kinematics), + 3. step closer, grasp each cup by its handle (visual correction on approach), + lift it into the cabinet, lower it until contact and release. + +The control flow is a generator: every `yield` emits one action. +""" + +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 hom(R, p): + M = np.eye(4) + M[:3, :3] = R + M[:3, 3] = p + return M + + +AXES = {'x': rx, 'y': ry, 'z': rz} + + +def _chain(side): + s = 1.0 if side == 'L' else -1.0 + 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 = {'L': [(np.array(x), rpy(*r), AXES[a]) for x, r, a in _chain('L')], + 'R': [(np.array(x), rpy(*r), AXES[a]) for x, r, a in _chain('R')]} + + +def torso(waist): + yaw, roll, pitch = waist + M = hom(rz(yaw), (0, 0, 0)) + M = M @ hom(rx(roll), (-0.0039635, 0, 0.044)) + M = M @ hom(ry(pitch), (0, 0, 0)) + return M + + +def fk(side, q, waist=(0, 0, 0), tool=(0.0, 0, 0)): + """Pose (4x4) of a point `tool` in the wrist-yaw frame, in the pelvis frame.""" + M = torso(waist) + for (xyz, R0, ax), qi in zip(CHAINS[side], q): + M = M @ hom(R0 @ ax(qi), xyz) + return M @ hom(np.eye(3), tool) + + +SAFE_LO = np.array([-3.0, -0.05, -1.3, -1.0, -1.2, -1.6, -1.6]) +SAFE_HI = np.array([1.0, 1.6, 1.3, 2.0, 1.2, 1.6, 1.6]) +POST_W = np.array([0.0, 0.02, 0.01, 0.0, 0.03, 0.01, 0.03]) +SEEDS = ([-1.5, 0.3, 0, 0.8, 0, 0, 0], [-2.0, 0.3, 0, 0.0, 0, 0.5, 0], [-1.0, 0.2, 0, 1.0, 0, 0, 0], + [-0.5, 0.2, 0, 0.5, 0, 0.5, 0], [0, 0, 0, 0, 0, 0, 0], [-0.8, 0.3, 0.3, -0.3, 0, 0.8, 0], + [0.3, 0.2, 0.2, -0.7, 0, 0.3, 0]) + + +def mirror(q): + q = np.array(q, float) + q[[1, 2, 4, 6]] *= -1 + return q + + +def limits(side): + lo, hi = SAFE_LO.copy(), SAFE_HI.copy() + if side == 'L': + return lo, hi + lo, hi = mirror(hi), mirror(lo) + return np.minimum(lo, hi), np.maximum(lo, hi) + + +def ik(side, pos, R, q0, waist, tool, qn, reg=0.01): + lo, hi = limits(side) + q0 = np.clip(np.asarray(q0, float), lo + 1e-3, hi - 1e-3) + + def res(q): + M = fk(side, q, waist, tool) + return np.concatenate([M[:3, 3] - pos, 0.1 * (M[:3, :3] - R).ravel(), reg * (q - qn), POST_W * q]) + + sol = least_squares(res, q0, bounds=(lo, hi)) + M = fk(side, sol.x, waist, tool) + return sol.x, np.linalg.norm(M[:3, 3] - pos), np.linalg.norm(M[:3, :3] - R) + + +def ik_multi(side, pos, R, q0, waist, tool): + seeds = [q0] + [s if side == 'L' else mirror(s) for s in SEEDS] + best = None + for i, s in enumerate(seeds): + q, e, oe = ik(side, np.asarray(pos, float), R, s, waist, tool, qn=q0) + c = e + 0.03 * oe + 0.004 * np.linalg.norm(q - q0) + if best is None or c < best[3]: + best = (q, e, oe, c) + if i == 0 and e < 0.005 and oe < 0.05: + break + return best[0], best[1], best[2] + + +def Rpitch(pitch, yaw=0.0): + return rz(yaw) @ ry(pitch) + + +# ----------------------------------------------------------------------------- wrist camera model +# Calibrated from counter edges seen from many arm poses (mount offset/rotation in +# the wrist-yaw frame, focal length in pixels for the 84x84 image). +MOUNT = np.array([1.00426192e-01, 1.63377606e-02, -7.96530148e-04, -1.72016415e-03, 6.93784492e-01, + -1.56295375e-02]) +FOC = 68.8746480 +TOOLS = {'L': (0.155, 0.016, -0.046), 'R': (0.155, -0.016, -0.046)} # grasp centre in wrist frame +LOOK_TOOL = (0.12, 0.0, 0.0) + + +def cam_pose(side, l): + tx, ty, tz, cr, cp, cy = MOUNT + s = 1.0 if side == 'L' else -1.0 + q = l[3:10] if side == 'L' else l[12:19] + M = fk(side, q, l[0:3]) + Wp = hom(rz(l[24]), (l[21], l[22], l[23])) + Mc = hom(rz(s * cy) @ ry(cp) @ rx(s * cr), (tx, s * ty, tz)) + C = Wp @ M @ Mc + return C[:3, :3], C[:3, 3] + + +def project(Rc, pc, X): + d = (np.asarray(X) - pc) @ Rc + u = 41.5 - FOC * d[..., 1] / d[..., 0] + v = 41.5 - FOC * d[..., 2] / d[..., 0] + return np.stack([u, v], -1), d[..., 0] + + +def ray(Rc, pc, uv): + u, v = uv + d = Rc @ np.array([1.0, -(u - 41.5) / FOC, -(v - 41.5) / FOC]) + return pc, d / np.linalg.norm(d) + + +def ray_plane_z(Rc, pc, uv, z): + p, d = ray(Rc, pc, uv) + return p + (z - p[2]) / d[2] * d + + +# ----------------------------------------------------------------------------- cups +Z_TOP = 0.806 # counter top height +CUP_R = 0.04 +RHV = 0.058 # radius of the visible handle loop +RHG = 0.062 # radius of the grasp point on the handle +ZG = Z_TOP + 0.052 +U_REF = 43.0 +PSI_MAX = 0.7 +RT = 0.085 # grasp point distance from the cup axis (fingers are long) +U_GRASP = 42.0 +CUP_W = 0.079 + + +def grey_mask(im): + im = im.astype(int) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + return (abs(r - g) < 7) & (abs(g - b) < 7) & (r > 85) & (r < 235) + + +def wood_mask(im): + im = im.astype(int) + return (im[..., 0] - im[..., 2] > 20) & (im[..., 0] > 50) + + +def detect_cups(im): + g = grey_mask(im).astype(np.uint8) + w = wood_mask(im) + n, lab, stats, _ = cv2.connectedComponentsWithStats(g, connectivity=4) + out = [] + H = im.shape[0] + for i in range(1, n): + x, y, ww, hh, area = stats[i] + if area < 25 or ww < 8: + continue + ys, xs = np.nonzero(lab == i) + below = tot = 0 + for u in range(x, x + ww): + col = ys[xs == u] + if len(col) == 0: + continue + vb = col.max() + tot += 1 + if vb + 1 < H and w[vb + 1:min(vb + 4, H), u].any(): + below += 1 + if tot == 0 or below < 0.5 * tot: + continue + uc = xs.mean() + sel = np.abs(xs - uc) <= max(2, ww * 0.25) + vb = ys[sel].max() + out.append(dict(bottom=(uc, vb + 0.5), left=x, right=x + ww - 1, stats=(x, y, ww, hh), + edge=(x <= 0 or x + ww >= im.shape[1]), label=i, lab=lab)) + return out + + +def handle_column(im, blob): + x, y, ww, hh = blob['stats'] + m = blob['lab'][y:y + hh, x:x + ww] == blob['label'] + g = im[y:y + hh, x:x + ww].astype(float).mean(2) + r0, r1 = int(0.3 * hh), int(0.9 * hh) + sc = np.zeros(ww) + for c in range(ww): + col = g[r0:r1, c][m[r0:r1, c]] + if len(col) > 4: + sc[c] = np.std(col) + if ww > 4: + sc[0] = sc[-1] = 0 + if sc.max() < 8: + return None + wts = np.clip(sc - 0.5 * sc.max(), 0, None) + return x + (np.arange(ww) * wts).sum() / wts.sum() + 0.5 + + +def locate_cup(side, l, blob, im): + Rc, pc = cam_pose(side, l) + P = ray_plane_z(Rc, pc, blob['bottom'], Z_TOP) + d = P - pc + d[2] = 0 + d /= np.linalg.norm(d) + C = P + CUP_R * d + uh = handle_column(im, blob) + if uh is None: + return C, None + uvc, dep = project(Rc, pc, np.array([[C[0], C[1], Z_TOP + 0.05]])) + s = np.clip(-(uh - uvc[0, 0]) * dep[0] / FOC / RHV, -1, 1) + view = pc[:2] - C[:2] + th = np.arctan2(view[1], view[0]) - np.arcsin(s) + return C, th + + +def wrapa(a): + return (a + np.pi) % (2 * np.pi) - np.pi + + +# ----------------------------------------------------------------------------- scene constants +BASE = (0.168, 0.0, 0.0) +BASE2 = (0.27, 0.0, 0.0) +DOORS = {'R': dict(bar=(0.648, -0.045), hinge=(0.696, -0.30), sgn=1.0), + 'L': dict(bar=(0.643, 0.047), hinge=(0.696, 0.30), sgn=-1.0)} +DOOR_Z = 1.16 +PLACE_Y = {'L': 0.085, 'R': -0.075} +NEUTRAL = {'L': (0.22, 0.22, 0.12), 'R': (0.22, -0.22, 0.12)} +GI = {'L': 19, 'R': 20} +SKIP_DOORS = False +FI = {'L': 10, 'R': 19} + + +class Policy: + def reset(self, obs, tools): + self.tools = tools + self.obs = obs + self.A = np.asarray(tools.hold_action(), dtype=np.float64) + self.A[[0, 1, 3]] = 0 + self.A[19] = self.A[20] = 0.0 + self.gen = self.script() + self.log = [] + + def act(self, obs, tools): + self.obs = obs + try: + a = next(self.gen) + except StopIteration: + self.gen = self.idle() + a = next(self.gen) + return np.asarray(a, dtype=np.float32) + + # ------------------------------------------------------------------ helpers + def lo(self): + return np.asarray(self.obs['low_dim_obs'], dtype=np.float64) + + def base_cmd(self, a, goal, tol=0.06, ytol=0.08): + l = self.lo() + x, y, yaw = goal + dx, dy = x - l[21], y - l[22] + c, s = np.cos(l[24]), np.sin(l[24]) + bx, by = c * dx + s * dy, -s * dx + c * dy + dyaw = wrapa(yaw - l[24]) + 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) + if np.hypot(bx, by) < tol: + vx = vy = 0.0 + elif sp < 0.07: + vx, vy = vx / sp * 0.07, vy / sp * 0.07 + a[0], a[1] = vx, vy + a[3] = np.clip(2.0 * dyaw, -0.5, 0.5) if abs(dyaw) > ytol else 0.0 + return np.hypot(bx, by), dyaw + + def emit(self, goal): + a = self.A.copy() + a[0] = a[1] = a[3] = 0.0 + if goal is not None: + self.base_cmd(a, goal) + return a + + def hold(self, n, goal=None): + for _ in range(n): + yield self.emit(goal) + + def move(self, B, n, goal=None): + A0 = self.A.copy() + B = np.asarray(B, dtype=np.float64) + for i in range(1, n + 1): + self.A = A0 + (B - A0) * (i / n) + yield self.emit(goal) + self.A = B.copy() + + def walk(self, goal, maxn=400, tol=0.02): + for _ in range(maxn): + a = self.A.copy() + d, dyaw = self.base_cmd(a, goal, tol=tol, ytol=0.03) + if d < tol and abs(dyaw) < 0.03: + break + yield a + yield from self.hold(5) + + def gripper(self, side, val, n=10, goal=None): + B = self.A.copy() + B[GI[side]] = val + yield from self.move(B, n, goal) + + def world_to_pelvis(self, pw): + l = self.lo() + c, s = np.cos(l[24]), np.sin(l[24]) + d = np.asarray(pw, float) - l[21:24] + return np.array([c * d[0] + s * d[1], -s * d[0] + c * d[1], d[2]]) + + def tool_world(self, side, tool=None): + l = self.lo() + q = l[3:10] if side == 'L' else l[12:19] + M = fk(side, q, l[0:3], TOOLS[side] if tool is None else tool) + return rz(l[24]) @ M[:3, 3] + l[21:24] + + def arm_to(self, side, pos_world, pitch, yaw_world=0.0, n=40, goal=None, tool=None): + l = self.lo() + q0 = l[3:10] if side == 'L' else l[12:19] + q, e, oe = ik_multi(side, self.world_to_pelvis(pos_world), Rpitch(pitch, yaw_world - l[24]), q0, l[0:3], + TOOLS[side] if tool is None else tool) + B = self.A.copy() + if side == 'L': + B[5:12] = q + else: + B[12:19] = q + yield from self.move(B, n, goal) + + def arms_to(self, tg, n=40, goal=None): + """tg: dict side -> (pos_world, pitch, yaw_world). Moves both arms together.""" + l = self.lo() + B = self.A.copy() + for side, (pos, pitch, yaw) in tg.items(): + q0 = l[3:10] if side == 'L' else l[12:19] + q, e, oe = ik_multi(side, self.world_to_pelvis(pos), Rpitch(pitch, yaw - l[24]), q0, l[0:3], TOOLS[side]) + if side == 'L': + B[5:12] = q + else: + B[12:19] = q + yield from self.move(B, n, goal) + + def arms_to_cl(self, tg, n=40, goal=None, iters=2, settle=8): + cmd = {k: np.asarray(v[0], float).copy() for k, v in tg.items()} + yield from self.arms_to(tg, n, goal) + for _ in range(iters): + yield from self.hold(settle, goal) + done = True + for side, (pos, pitch, yaw) in tg.items(): + err = np.asarray(pos, float) - self.tool_world(side) + if np.linalg.norm(err) > 0.005: + done = False + cmd[side] = cmd[side] + 0.8 * np.clip(err, -0.04, 0.04) + if done: + break + yield from self.arms_to({k: (cmd[k], v[1], v[2]) for k, v in tg.items()}, max(12, n // 3), goal) + + def arm_to_cl(self, side, pos_world, pitch, yaw_world=0.0, n=40, goal=None, iters=2, settle=8): + tgt = np.asarray(pos_world, float) + cmd = tgt.copy() + yield from self.arm_to(side, cmd, pitch, yaw_world, n, goal) + for _ in range(iters): + yield from self.hold(settle, goal) + err = tgt - self.tool_world(side) + if np.linalg.norm(err) < 0.005: + break + cmd = cmd + 0.8 * np.clip(err, -0.04, 0.04) + yield from self.arm_to(side, cmd, pitch, yaw_world, max(12, n // 3), goal) + self.last_err = self.tool_world(side) - tgt + + def neutral(self, side, n=40, goal=BASE): + x, y, z = NEUTRAL[side] + l = self.lo() + P = rz(l[24]) @ np.array([x, y, z]) + l[21:24] + yield from self.arm_to(side, P, 0.0, l[24], n, goal) + + def img(self, side): + return np.asarray(self.tools.image('left_wrist' if side == 'L' else 'right_wrist')) + + def idle(self): + while True: + yield self.emit(self.goal) + + # ------------------------------------------------------------------ skills + def open_doors(self, phi_end=1.7, cap=1.0, p=-0.5, nwp=17, nper=10): + goal = BASE + ax = np.array([np.cos(p), 0, -np.sin(p)]) + bars = {k: np.array([d['bar'][0], d['bar'][1], DOOR_Z]) for k, d in DOORS.items()} + B = self.A.copy() + B[19] = B[20] = 0.0 + yield from self.move(B, 8, goal) + for back, n in ((0.10, 45), (0.05, 20), (0.0, 20)): + yield from self.arms_to_cl({k: (bars[k] - back * ax, p, 0.0) for k in bars}, n, goal) + B = self.A.copy() + B[19] = B[20] = 1.0 + yield from self.move(B, 20, goal) + yield from self.hold(8, goal) + ok = {k: self.lo()[FI[k]] > -0.0185 for k in bars} + self.log.append(('door_grasp', ok)) + for k in bars: + if not ok[k]: + self.A[GI[k]] = 0.0 + sides = [k for k in bars if ok[k]] + for k in range(1, nwp + 1): + tg = {} + for side in sides: + d = DOORS[side] + hinge = np.array(d['hinge']) + r0 = bars[side][:2] - hinge + phi = d['sgn'] * phi_end * k / nwp + c, s = np.cos(phi), np.sin(phi) + tgt = np.array([hinge[0] + c * r0[0] - s * r0[1], hinge[1] + s * r0[0] + c * r0[1], DOOR_Z]) + tg[side] = (tgt, p, d['sgn'] * min(abs(phi), cap)) + if tg: + yield from self.arms_to(tg, nper, goal) + yield from self.hold(6, goal) + B = self.A.copy() + B[19] = B[20] = 0.0 + yield from self.move(B, 10, goal) + tg1, tg2 = {}, {} + for side in bars: + yaw = DOORS[side]['sgn'] * cap if side in sides else 0.0 + hd = np.array([np.cos(yaw), np.sin(yaw), 0]) + P1 = self.tool_world(side) - 0.06 * hd + tg1[side] = (P1, p, yaw) + tg2[side] = (P1 + np.array([-0.12, 0, -0.05]), p, yaw) + yield from self.arms_to(tg1, 15, goal) + yield from self.arms_to(tg2, 20, goal) + l = self.lo() + yield from self.arms_to({k: (rz(l[24]) @ np.array(NEUTRAL[k]) + l[21:24], 0.0, l[24]) for k in bars}, 35, goal) + return ok + + def look_cups(self, goal): + self.A[19] = self.A[20] = 0.0 + l = self.lo() + for side, y in (('L', 0.15), ('R', -0.15)): + P = rz(l[24]) @ np.array([0.30, y, 0.2]) + l[21:24] + yield from self.arm_to(side, P, -0.35, l[24], 30 if side == 'L' else 45, goal, tool=LOOK_TOOL) + yield from self.hold(12, goal) + found = [] + for side in ('L', 'R'): + im = self.img(side) + l = self.lo() + for b in detect_cups(im): + C, th = locate_cup(side, l, b, im) + if 0.6 < C[0] < 0.95 and abs(C[1]) < 0.32: + found.append((side, C, th, b['edge'])) + cups = [] + for side, C, th, edge in sorted(found, key=lambda f: f[3]): + for c in cups: + if np.linalg.norm(c['C'][:2] - C[:2]) < 0.06: + if not edge: + c['obs'].append((C, th)) + break + else: + cups.append(dict(C=C, obs=[(C, th)])) + self.cups = [] + for c in cups: + Cs = np.array([o[0] for o in c['obs']]) + ths = [o[1] for o in c['obs'] if o[1] is not None] + th = np.arctan2(np.mean(np.sin(ths)), np.mean(np.cos(ths))) if ths else np.pi + self.cups.append((Cs.mean(0), th)) + self.log.append(('cups', [(np.round(C, 3).tolist(), round(float(th), 2)) for C, th in self.cups])) + + def cup_blob(self, side, C): + """Blob of the cup whose centre column is closest to the projection of C.""" + im = self.img(side) + bl = detect_cups(im) + if not bl: + return im, None + Rc, pc = cam_pose(side, self.lo()) + uv, dep = project(Rc, pc, np.array([[C[0], C[1], Z_TOP + 0.05]])) + up = uv[0, 0] if dep[0] > 0.02 else 41.5 + b = min(bl, key=lambda b: abs((b['left'] + b['right']) / 2 - up)) + if abs((b['left'] + b['right']) / 2 - up) > 30: + return im, None + return im, b + + def measure_cup(self, side, C): + """Cup centre from the contact point of its bottom with the counter (close view).""" + im, b = self.cup_blob(side, C) + if b is None: + return None + x, y, ww, hh = b['stats'] + if x <= 0 or x + ww >= 84 or y + hh >= 83: + return None + return locate_cup(side, self.lo(), b, im) + + def handle_u(self, side, C): + im, b = self.cup_blob(side, C) + if b is None: + return None + return handle_column(im, b) + + def grasp_cup(self, side, C, th, goal, pp=-0.05): + C = np.array(C, float) + yield from self.gripper(side, 0.0, 8, goal) + + lo_psi, hi_psi = (-0.35, PSI_MAX) if side == 'L' else (-PSI_MAX, 0.35) + + def frame(C, th): + psi = float(np.clip(wrapa(th + np.pi), lo_psi, hi_psi)) + th = psi + np.pi + a = np.array([np.cos(psi), np.sin(psi), 0.0]) + lat = np.array([-np.sin(psi), np.cos(psi), 0.0]) + T = np.array([C[0] + RT * np.cos(th), C[1] + RT * np.sin(th), ZG]) + return psi, a, lat, T + + for back, n in ((0.16, 32), (0.10, 16)): + psi, a, lat, T = frame(C, th) + yield from self.arm_to_cl(side, T - back * a + np.array([0, 0, 0.05]), pp, psi, n, goal, iters=1) + m = self.measure_cup(side, C) + if m is not None and np.linalg.norm(m[0][:2] - C[:2]) < 0.08: + C[:2] = m[0][:2] + if m[1] is not None and abs(wrapa(m[1] - th)) < 0.35: + th = wrapa(th + 0.5 * wrapa(m[1] - th)) + l = self.lo() + if np.hypot(l[21] - self.goal[0], l[22] - self.goal[1]) > 0.03: + yield from self.walk(self.goal, maxn=80, tol=0.015) + yield from self.hold(8) + psi, a, lat, T = frame(C, th) + Tb = T - 0.045 * a + for it in range(3): + yield from self.arm_to_cl(side, Tb, pp, psi, 20 if it == 0 else 12, goal, iters=2 if it == 0 else 1) + uh = self.handle_u(side, C) + if uh is None: + break + dl = -(uh - U_GRASP) * 0.10 / FOC + Tb = Tb + dl * lat + T = T + dl * lat + C = C + dl * lat + if abs(uh - U_GRASP) < 2.0: + break + yield from self.arm_to_cl(side, T, pp, psi, 20, goal) + yield from self.gripper(side, 1.0, 20, goal) + yield from self.hold(8, goal) + self.grasp_ok = self.lo()[FI[side]] > -0.0185 + self.grasp_psi = psi + self.log.append(('grasp', side, bool(self.grasp_ok), np.round(C, 3).tolist(), round(float(th), 2), + np.round(self.last_err, 3).tolist())) + + def place_cup(self, side, y_place, x_center=0.82, z_carry=1.175, rel_x=0.42, pc=-0.1): + hx = x_center - RT + tw = self.tool_world(side) + psi0 = self.grasp_psi + # pull the cup out from under the cabinet, then step back + yield from self.arm_to_cl(side, (0.53, tw[1], ZG + 0.04), 0.0, psi0, 30, None, iters=1) + self.goal = (0.06, 0.0, 0.0) + yield from self.walk(self.goal, maxn=150) + yield from self.hold(10) + l = self.lo() + yield from self.arm_to_cl(side, (l[21] + rel_x, y_place, z_carry), pc, 0.0, 40, None) + # walk in: the arm is held fixed, the body carries the cup into the cabinet + tw = self.tool_world(side) + bx = min(self.lo()[21] + (hx - tw[0]), 0.25) + self.goal = (bx, 0.0, 0.0) + yield from self.walk(self.goal, maxn=150, tol=0.015) + yield from self.hold(10) + yield from self.arm_to_cl(side, (hx, y_place, z_carry), pc, 0.0, 25, None) + # lower until the cup stops going down + tz = self.tool_world(side)[2] + cmdz = tz - 0.01 + stall = 0 + while tz > 1.09: + cmdz -= 0.006 + yield from self.arm_to(side, (hx, y_place, cmdz), pc, 0.0, 6, None) + yield from self.hold(2) + tz_new = self.tool_world(side)[2] + stall = stall + 1 if tz - tz_new < 0.002 else 0 + tz = tz_new + if stall >= 2: + break + self.log.append(('placed_z', round(float(tz), 3), int(self.obs['t']))) + yield from self.gripper(side, 0.0, 12) + yield from self.hold(6) + # step back with the arm fixed so the fingers slide off the handle + self.goal = (self.lo()[21] - 0.16, 0.0, 0.0) + yield from self.walk(self.goal, maxn=120) + yield from self.neutral(side, 30, self.goal) + + # ------------------------------------------------------------------ main script + def script(self): + self.goal = BASE + yield from self.neutral('L', 25) + yield from self.neutral('R', 25) + if not SKIP_DOORS: + yield from self.open_doors() + self.log.append(('t_doors', int(self.obs['t']))) + yield from self.look_cups(BASE) + yield from self.neutral('L', 25) + yield from self.neutral('R', 25) + cups = sorted(self.cups, key=lambda c: c[0][1])[:2] + + def cost(side, c): + sg = 1.0 if side == 'L' else -1.0 + psi = wrapa(c[1] + np.pi) + return max(0.0, -sg * psi) + 3.0 * max(0.0, -sg * c[0][1]) + + if len(cups) == 2: + slots = [PLACE_Y['R'], PLACE_Y['L']] + else: + slots = [PLACE_Y['L' if c[0][1] > 0 else 'R'] for c in cups] + jobs = [('L' if cost('L', c) < cost('R', c) else 'R', c, y) for c, y in zip(cups, slots)] + failed = [] + for side, (C, th), y in jobs: + ok = yield from self.do_cup(side, C, th, y) + if not ok: + failed.append((side, C, y)) + for side, C, y in failed: + if self.obs['t'] > 1950: + break + self.goal = BASE2 + yield from self.walk(BASE2) + yield from self.look_cups(None) + yield from self.neutral('L', 20, None) + yield from self.neutral('R', 20, None) + cand = [c for c in self.cups if np.linalg.norm(c[0][:2] - C[:2]) < 0.15] + if not cand: + continue + C2, th2 = min(cand, key=lambda c: np.linalg.norm(c[0][:2] - C[:2])) + yield from self.do_cup(side, C2, th2, y) + + def do_cup(self, side, C, th, y_place): + bx = float(np.clip(C[0] - RT - 0.40, 0.22, 0.30)) + self.goal = (bx, 0.0, 0.0) + yield from self.walk(self.goal) + yield from self.hold(10) + yield from self.grasp_cup(side, C, th, None) + self.log.append(('t_grasp', int(self.obs['t']))) + if self.grasp_ok: + yield from self.place_cup(side, y_place) + self.log.append(('t_place', int(self.obs['t']))) + return True + yield from self.gripper(side, 0.0, 8, None) + tw = self.tool_world(side) + yield from self.arm_to(side, tw + np.array([-0.08, 0, 0.04]), 0.0, self.grasp_psi, 15, None) + yield from self.neutral(side, 30, None) + return False diff --git a/policies/put_cups/opus-s2/cupvision.py b/policies/put_cups/opus-s2/cupvision.py new file mode 100644 index 0000000000000000000000000000000000000000..2f1e81d1119123a311fda4e48e0a3c3c26c99a04 --- /dev/null +++ b/policies/put_cups/opus-s2/cupvision.py @@ -0,0 +1,272 @@ +"""Cup detection in the wrist cameras and stereo localisation (hand-written geometry).""" +import numpy as np +import cv2 + +from g1kin import cam_world, pix_ray + + +def cup_mask(im): + im = np.asarray(im, dtype=np.uint8) + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + return ((hsv[:, :, 1] < 45) & (hsv[:, :, 2] > 105)).astype(np.uint8) + + +def cup_blobs(im, min_area=60): + """Return list of dicts describing gray cup blobs, sorted left to right.""" + m = cup_mask(im) + n, lab, st, cen = cv2.connectedComponentsWithStats(m) + g = np.asarray(im, dtype=np.float64).mean(2) + out = [] + for i in range(1, n): + x, y, w, h, a = st[i] + if a < min_area or h < 8: + continue + mm = lab == i + rows = np.where(mm.any(1))[0] + top, bot = rows.min(), rows.max() + # body width from the rim rows (the handle starts below the rim) + rim = [r for r in range(top + 1, min(top + 4, bot))] + a_ = min(np.where(mm[r])[0].min() for r in rim) + b_ = max(np.where(mm[r])[0].max() for r in rim) + # widen with the lower part using the median row extent + lefts = np.array([np.where(mm[r])[0].min() for r in rows]) + rights = np.array([np.where(mm[r])[0].max() for r in rows]) + a_ = min(a_, int(np.median(lefts))) + b_ = max(b_, int(np.median(rights))) + # protrusions (handle seen from the side) + prot = mm.copy() + prot[:, a_ - 1:b_ + 2] = False + prot[:top + 3] = False + pu = np.where(prot) + body = mm.copy() + body[:, :a_ + 2] = False + body[:, b_ - 1:] = False + body[:top + 4] = False + body[max(top + 4, bot - 2):] = False + med = np.median(g[body]) if body.any() else 200 + dark = body & (g < med - 18) + du = np.where(dark) + handle = None + kind = None + if len(pu[0]) >= 4: + handle = (pu[1].mean(), pu[0].mean()) + kind = "side" + elif len(du[0]) >= 3: + handle = (du[1].mean(), du[0].mean()) + kind = "front" + out.append(dict(top=top, bot=bot, a=a_, b=b_, uc=(a_ + b_) / 2.0, area=a, + handle=handle, kind=kind, ndark=len(du[0]), nprot=len(pu[0]))) + out.sort(key=lambda d: d["uc"]) + return out + + +Z_BOT = 0.84 # counter top (cup bottom) height +R_CUP = 0.045 # cup body radius + + +def mono_cup(lo, side, b): + """Cup axis xy and handle direction (unit xy or None) from one camera blob.""" + C = cam_world(lo, side) + o, d = pix_ray(C, side, b["uc"], b["bot"] + 0.5) + s = (Z_BOT - o[2]) / d[2] + p = o + s * d + v = d[:2] / np.linalg.norm(d[:2]) + axis = p[:2] + R_CUP * v + hdir = None + if b["handle"] is not None: + w2 = max(3.0, (b["b"] - b["a"]) / 2.0) + off = (b["handle"][0] - b["uc"]) / w2 + # pixel u grows to the camera's right; camera right in world ~ (v_y, -v_x) + r = np.array([v[1], -v[0]]) + if b["kind"] == "side": + al = np.sign(off) * np.radians(90) + else: + al = np.arcsin(np.clip(off * 0.7, -1, 1)) + hdir = -np.cos(al) * v + np.sin(al) * r + return axis, hdir + + +def perceive(lo, imL, imR): + """Fuse mono detections of both wrist cameras into a list of cups.""" + dets = [] + for side, im in ((1, imL), (-1, imR)): + for b in cup_blobs(im): + if b["a"] <= 1 or b["b"] >= 82: + continue + w = b["b"] - b["a"] + if w > 24 or w < 8: + continue + axis, hdir = mono_cup(lo, side, b) + dets.append(dict(side=side, axis=axis, hdir=hdir, b=b)) + cups = [] + for dt in dets: + for c in cups: + if np.linalg.norm(c["axes"][0] - dt["axis"]) < 0.06 and dt["side"] not in c["sides"]: + c["axes"].append(dt["axis"]) + c["sides"].append(dt["side"]) + if dt["hdir"] is not None: + c["hdirs"].append(dt["hdir"]) + break + else: + cups.append(dict(axes=[dt["axis"]], sides=[dt["side"]], hdirs=[dt["hdir"]] if dt["hdir"] is not None else [])) + out = [] + for c in cups: + xy = np.mean(c["axes"], 0) + if c["hdirs"]: + h = np.mean(c["hdirs"], 0) + h = h / max(1e-6, np.linalg.norm(h)) + else: + h = None + out.append(dict(xy=xy, hdir=h, n=len(c["axes"]))) + return out + + +def wood_mask(im): + hsv = cv2.cvtColor(np.asarray(im, dtype=np.uint8), cv2.COLOR_RGB2HSV) + return (hsv[:, :, 1] > 50) & (hsv[:, :, 0] >= 5) & (hsv[:, :, 0] <= 30) + + +def cup_measure(im, u_pred=None, w_pred=None): + """Silhouette features of the cup nearest u_pred (or the largest one).""" + im = np.asarray(im, dtype=np.uint8) + m = cup_mask(im) + wood = wood_mask(im) + g = np.asarray(im, dtype=np.float64).mean(2) + n, lab, st, cen = cv2.connectedComponentsWithStats(m) + best = None + for i in range(1, n): + x, y, w, h, a = st[i] + if a < 80 or h < 8: + continue + # a cup stands on the counter: wood right below its bottom row + yb = y + h + if yb < im.shape[0] - 1: + below = wood[min(im.shape[0] - 1, yb):min(im.shape[0], yb + 3), x:x + w] + if below.size and below.mean() < 0.3: + continue + if w_pred is not None and not (0.45 * w_pred <= w <= 2.0 * w_pred): + continue + score = a if u_pred is None else -abs(cen[i][0] - u_pred) + 0.02 * a + if best is None or score > best[0]: + best = (score, i) + if best is None: + return None + i = best[1] + mm = lab == i + rows = np.where(mm.any(1))[0] + top, bot = rows.min(), rows.max() + ext = np.array([[np.where(mm[r])[0].min(), np.where(mm[r])[0].max()] for r in range(top, bot + 1)]) + H = bot - top + sel = list(range(int(0.12 * H), max(int(0.12 * H) + 1, int(0.2 * H)))) + \ + list(range(int(0.85 * H), max(int(0.85 * H) + 1, int(0.93 * H)))) + rimL = float(np.median(ext[sel, 0])) + rimR = float(np.median(ext[sel, 1])) + zone = ext[int(0.25 * H):max(int(0.25 * H) + 1, int(0.85 * H))] + protL = np.clip(rimL - zone[:, 0], 0, None) + protR = np.clip(zone[:, 1] - rimR, 0, None) + body = np.zeros_like(mm) + for k, r in enumerate(range(top, bot + 1)): + l, rr = ext[k] + body[r, int(max(l, rimL)) + 2:int(min(rr, rimR)) - 1] = True + body[:top + int(0.2 * H)] = False + body[bot - int(0.1 * H):] = False + body &= mm + med = np.median(g[body]) if body.any() else 0 + dk = body & (g < med - 20) + du = np.where(dk) + touch = (ext[:, 0].min() <= 0) or (ext[:, 1].max() >= im.shape[1] - 1) or bot >= im.shape[0] - 1 or top <= 0 + uc = (rimL + rimR) / 2 + w = rimR - rimL + hoff = None + if protL.max() >= 3 and protL.max() > protR.max() + 1: + hoff = -1.0 + elif protR.max() >= 3 and protR.max() > protL.max() + 1: + hoff = 1.0 + elif len(du[0]) >= 4: + mu = du[1].mean() + ext_u = np.percentile(du[1], 10) if mu < uc else np.percentile(du[1], 90) + hoff = float(np.clip((ext_u - uc) / max(2.0, w / 2), -0.99, 0.99)) + hu = None + if len(du[0]) >= 15: + hu = float(du[1].mean()) + elif hoff is not None and abs(hoff) >= 1.0: + hu = rimL - protL.max() / 2 if hoff < 0 else rimR + protR.max() / 2 + elif len(du[0]) >= 4: + hu = float(du[1].mean()) + return dict(top=top, bot=bot, uc=uc, w=w, hoff=hoff, touch=touch, area=int(mm.sum()), hu=hu) + + +def pregrasp_handle(im, upred=42.0): + """Column of the handle (dark outline inside the cup silhouette) in the top part of a + wrist image taken just before the grasp approach.""" + im = np.asarray(im, np.uint8) + m = cup_mask(im) + m[36:] = 0 + g = im.astype(float).mean(2) + n, lab, st, cen = cv2.connectedComponentsWithStats(m) + best = None + for i in range(1, n): + if st[i, 4] < 60: + continue + sc = -abs(cen[i][0] - upred) + if best is None or sc > best[0]: + best = (sc, i) + if best is None: + return None + mm = lab == best[1] + cols = [] + for r in range(0, 36): + xs = np.where(mm[r])[0] + if len(xs) < 5: + continue + a, b = xs.min(), xs.max() + seg = g[r, a + 2:b - 1] + if len(seg) < 3: + continue + med = np.median(g[r][mm[r]]) + cols += list(np.where(seg < med - 25)[0] + a + 2) + if len(cols) < 8: + return None + return float(np.median(cols)) + + +def _plane(lo, side, u, v1, v2): + C = cam_world(lo, side) + o, d1 = pix_ray(C, side, u, v1) + _, d2 = pix_ray(C, side, u, v2) + nrm = np.cross(d1, d2) + nrm /= np.linalg.norm(nrm) + return o, nrm + + +def axis_xy(lo, bl, br): + """Intersect the two planes through the cup's image centre lines; return x, y of the vertical axis.""" + oL, nL = _plane(lo, 1, bl["uc"], bl["top"], bl["bot"]) + oR, nR = _plane(lo, -1, br["uc"], br["top"], br["bot"]) + # line direction + dvec = np.cross(nL, nR) + dvec /= np.linalg.norm(dvec) + # point on both planes closest to the origin of left cam, at z ~ 0.9 + A = np.array([nL, nR, [0, 0, 1.0]]) + b = np.array([nL @ oL, nR @ oR, 0.92]) + p = np.linalg.solve(A, b) + return p, dvec + + +def ray_point(lo, side, u, v): + return pix_ray(cam_world(lo, side), side, u, v) + + +def closest_on_vertical(o, d, xy): + """z where ray (o,d) passes closest to the vertical line through xy.""" + w = o[:2] - xy + dd = d[:2] + s = -(w @ dd) / max(1e-9, dd @ dd) + return o + s * d + + +def triangulate(o1, d1, o2, d2): + A = np.stack([d1, -d2], 1) + s = np.linalg.lstsq(A, o2 - o1, rcond=None)[0] + p1, p2 = o1 + s[0] * d1, o2 + s[1] * d2 + return (p1 + p2) / 2, np.linalg.norm(p1 - p2) diff --git a/policies/put_cups/opus-s2/episodes.csv b/policies/put_cups/opus-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f07188c1e36ce62841ee9aa30874cd299fb4de7e --- /dev/null +++ b/policies/put_cups/opus-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/opus-s2/g1kin.py b/policies/put_cups/opus-s2/g1kin.py new file mode 100644 index 0000000000000000000000000000000000000000..73aadde8b47241f4a88faaee026271568847862d --- /dev/null +++ b/policies/put_cups/opus-s2/g1kin.py @@ -0,0 +1,168 @@ +"""Kinematics + camera model helpers for the G1 policy (hand-written geometry).""" +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 qmat(w, x, y, z): + n = np.sqrt(w * w + x * x + y * y + z * z) + w, x, y, z = w / n, x / n, y / n, z / n + return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]) + + +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 + + +LO = np.array([-3.0892, -0.1, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +HI = np.array([0.4, 2.2515, 2.618, 1.65, 1.97222, 1.61443, 1.61443]) + + +def limits(side): + if side > 0: + return LO, HI + lo, hi = LO.copy(), HI.copy() + lo[1], hi[1] = -HI[1], -LO[1] + return lo, hi + + +_SH = {s: T(qmat(0.990264, s * 0.139201, 0, 0), (0.0039563, s * 0.10022, 0.23778)) for s in (1, -1)} +_RO = {s: T(qmat(0.990268, -s * 0.139172, 0, 0), (0, s * 0.038, -0.013831)) for s in (1, -1)} + + +def torso(waist): + return T(rz(waist[0])) @ T(p=(-0.0039635, 0, 0.035)) @ T(rx(waist[1])) @ T(p=(0, 0, 0.019)) @ T(ry(waist[2])) + + +def wrist(q, side): + """torso frame -> wrist_yaw_link frame""" + s = side + M = _SH[s] @ T(ry(q[0])) @ _RO[s] @ T(rx(q[1])) + M = M @ T(rz(q[2]), (0, s * 0.00624, -0.1032)) + M = M @ T(ry(q[3]), (0.015783, 0, -0.080518)) + M = M @ T(rx(q[4]), (0.1, s * 0.00188791, -0.01)) + M = M @ T(ry(q[5]), (0.038, 0, 0)) + M = M @ T(rz(q[6]), (0.046, 0, 0)) + return M + + +def pelvis(lo): + x, y, z, yaw = lo[21:25] + # the pelvis tilts back a little when the controller leans the torso forward + pp = -0.14 * (lo[2] - 0.053) + return T(rz(yaw), (x, y, z)) @ T(ry(pp)) + + +def arm_q(lo, side): + return np.asarray(lo[3:10] if side > 0 else lo[12:19], float) + + +def hand_world(lo, side, q=None, tip=0.0): + """world pose of a point `tip` metres along the gripper axis""" + if q is None: + q = arm_q(lo, side) + return pelvis(lo) @ torso(lo[0:3]) @ wrist(q, side) @ T(p=(tip, 0, 0)) + + +# wrist camera model (bundle-adjusted from arm motion; mirrored for right) +CAM = {1: np.array([0.1392, -0.0028, 0.0246, 0.675, 0.0861, 0.039, 66.25, 38.79, 40.06]), + -1: np.array([0.1742, -0.007, 0.0097, 0.7195, 0.0272, -0.0147, 64.41, 41.15, 41.34])} + + +def cam_mount(side): + P = CAM[side] + s = side + return T(p=(P[0], s * P[1], P[2])) @ T(rz(s * P[4])) @ T(ry(P[3])) @ T(rx(s * P[5])) + + +def cam_world(lo, side, q=None): + if q is None: + q = arm_q(lo, side) + return pelvis(lo) @ torso(lo[0:3]) @ wrist(q, side) @ cam_mount(side) + + +def pix_ray(C, side, u, v): + P = CAM[side] + d = np.array([1.0, (P[7] - u) / P[6], (P[8] - v) / P[6]]) + d = C[:3, :3] @ d + return C[:3, 3], d / np.linalg.norm(d) + + +def project(C, side, X): + P = CAM[side] + Ci = np.linalg.inv(C) + X = np.atleast_2d(X) + pc = (Ci[:3, :3] @ X.T).T + Ci[:3, 3] + return np.stack([P[7] - P[6] * pc[:, 1] / pc[:, 0], P[8] - P[6] * pc[:, 2] / pc[:, 0]], 1), pc[:, 0] + + +def triangulate(o1, d1, o2, d2): + A = np.stack([d1, -d2], 1) + s = np.linalg.lstsq(A, o2 - o1, rcond=None)[0] + p1, p2 = o1 + s[0] * d1, o2 + s[1] * d2 + return (p1 + p2) / 2, np.linalg.norm(p1 - p2) + + +QNOM = np.array([-0.9, 0.25, 0.0, 0.9, 0.0, 0.0, 0.0]) + + +def ik(side, Tbase, pos, xdir=None, zdir=None, q0=None, tip=0.19, wrot=0.35, iters=60, qref=None, wref=0.02, lam=1e-3, wnom=0.004): + """Damped least squares IK. Tbase: world->torso frame (pelvis@torso). pos/xdir/zdir in world.""" + lo, hi = limits(side) + q = np.zeros(7) if q0 is None else np.clip(np.asarray(q0, float), lo, hi) + qr = q.copy() if qref is None else np.asarray(qref, float) + qnom = QNOM.copy() + qnom[1] *= side + Bi = np.linalg.inv(Tbase) + p_t = Bi[:3, :3] @ pos + Bi[:3, 3] + x_t = None if xdir is None else Bi[:3, :3] @ xdir + z_t = None if zdir is None else Bi[:3, :3] @ zdir + + def res(q): + M = wrist(q, side) @ T(p=(tip, 0, 0)) + r = [M[:3, 3] - p_t] + if x_t is not None: + r.append(wrot * (M[:3, 0] - x_t)) + if z_t is not None: + r.append(wrot * (M[:3, 2] - z_t)) + r.append(wref * (q - qr)) + r.append(wnom * (q - qnom)) + return np.concatenate(r) + + eps = 1e-5 + for _ in range(iters): + r = res(q) + J = np.zeros((len(r), 7)) + for j in range(7): + dq = np.zeros(7) + dq[j] = eps + J[:, j] = (res(q + dq) - r) / eps + step = np.linalg.solve(J.T @ J + lam * np.eye(7), -J.T @ r) + n = np.linalg.norm(step) + if n > 0.3: + step *= 0.3 / n + q = np.clip(q + step, lo, hi) + if n < 1e-5: + break + M = wrist(q, side) @ T(p=(tip, 0, 0)) + return q, np.linalg.norm(M[:3, 3] - p_t) diff --git a/policies/put_cups/opus-s2/policy.py b/policies/put_cups/opus-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a4fde5507486e06a322fbd7d798257361a304ac9 --- /dev/null +++ b/policies/put_cups/opus-s2/policy.py @@ -0,0 +1,592 @@ +"""Put the cups from the counter into the wall cabinet (Unitree G1, scripted). + +Structure: the task is a tree of generator "phases". Each `yield` is one control +tick; `act` advances the phase generator by one tick and then computes the action +from the current arm targets. Arms are driven in Cartesian space with a damped +least-squares IK on the G1 arm kinematics (g1kin.py); cups and door bars are +located with the wrist cameras (cupvision.py). + +Sequence: open both doors together (grab the bars, swing them about the hinges), +locate both cups, grasp both handles, pull the cups out, step back, lift them +above the cabinet floor, step forward, lower them onto the shelf, release. +""" + +import numpy as np + +from g1kin import (pelvis, torso, hand_world, cam_world, pix_ray, project, ik, T, wrist) + +GT = 0.19 # gripper axis point that is used as grasp point + + +def pitched(yaw, pitch): + """Gripper x axis (approach) and z axis for a yaw / upward pitch.""" + x = np.array([np.cos(yaw) * np.cos(pitch), np.sin(yaw) * np.cos(pitch), np.sin(pitch)]) + z = np.array([-np.cos(yaw) * np.sin(pitch), -np.sin(yaw) * np.sin(pitch), np.cos(pitch)]) + return x, z + + +def smooth(a): + a = min(1.0, max(0.0, a)) + return a * a * (3 - 2 * a) + + +def par(*gens): + """Run several phase generators in lock step.""" + gens = list(gens) + while gens: + alive = [] + for g in gens: + try: + next(g) + alive.append(g) + except StopIteration: + pass + gens = alive + if gens: + yield + + +class Policy: + DEBUG = False + + def reset(self, obs, tools): + self.obs = obs + self.tools = tools + self.hold = np.asarray(tools.hold_action(), dtype=np.float64) + self.t = 0 + self.q = {1: np.zeros(7), -1: np.zeros(7)} + self.I = {1: np.zeros(7), -1: np.zeros(7)} + self.cart = {1: None, -1: None} + self.err = {1: 0.0, -1: 0.0} + self.g = [0.0, 0.0] + self.height, self.pitch = 0.74, 0.0 + self.hold_xy = None + self.arrived = False + self.walking = False + self.ki = {1: 0.03, -1: 0.03} + self.rate = 0.03 + self.snaps = [] + self.cups = {} + self.held = {1: False, -1: False} + self.gen = self._main() + + # ------------------------------------------------------------------ utils + @property + def lo(self): + return np.asarray(self.obs["low_dim_obs"], dtype=np.float64) + + def snap(self, label=""): + if self.DEBUG: + self.snaps.append((self.t, label)) + + def base_frame(self): + lo = self.lo + return pelvis(lo) @ torso(lo[0:3]) + + def hand(self, side, tip=GT): + return hand_world(self.lo, side, tip=tip) + + def cmd_hand(self, s): + return (self.base_frame() @ wrist(self.q[s], s) @ T(p=(GT, 0, 0)))[:3, 3] + + def _base_cmd(self): + vx = vy = wz = 0.0 + if self.hold_xy is not None: + gx, gy, gyaw = self.hold_xy + lo = self.lo + x, y, yaw = lo[21], lo[22], lo[24] + ex, ey = gx - x, gy - y + c, s = np.cos(yaw), np.sin(yaw) + bx, by = c * ex + s * ey, -s * ex + c * ey + en = np.hypot(bx, by) + eyaw = (gyaw - yaw + np.pi) % (2 * np.pi) - np.pi + if en > 0.03 or abs(eyaw) > 0.06: + self.walking = True + if en < 0.012 and abs(eyaw) < 0.03: + self.walking = False + self.arrived = True + self.hold_xy = None + return 0.0, 0.0, 0.0 + if self.walking: + vx, vy = 2.0 * bx, 2.0 * by + sp = np.hypot(vx, vy) + vmax = 0.12 if (self.held[1] or self.held[-1]) else 0.2 + if sp > vmax: + vx, vy = vx * vmax / sp, vy * vmax / sp + sp = np.hypot(vx, vy) + if 1e-6 < sp < 0.07: + vx, vy = vx * 0.07 / sp, vy * 0.07 / sp + if abs(eyaw) > 0.01: + wz = float(np.clip(2.0 * eyaw, -0.3, 0.3)) + return vx, vy, wz + + def _action(self): + lo = self.lo + raw = self.hold.copy() + vx, vy, wz = self._base_cmd() + raw[0], raw[1], raw[2], raw[3], raw[4] = vx, vy, self.height, wz, self.pitch + B = None + for side in (1, -1): + c = self.cart[side] + if c is None: + continue + if isinstance(c, tuple): + qd = c[1] if c[0] == "joint" else c[1](self.t) + dq = np.clip(qd - self.q[side], -self.rate, self.rate) + self.q[side] = self.q[side] + dq + else: + if B is None: + B = self.base_frame() + pos, xd, zd = c(self.t) + qn, e = ik(side, B, pos, xd, zd, q0=self.q[side], tip=GT, lam=0.01) + dq = np.clip(qn - self.q[side], -self.rate, self.rate) + self.q[side] = self.q[side] + dq + self.err[side] = e + qm = lo[3:10] if side > 0 else lo[12:19] + self.I[side] = np.clip(self.I[side] + self.ki[side] * (self.q[side] - qm), -0.25, 0.25) + raw[5:12] = self.q[1] + self.I[1] + raw[12:19] = self.q[-1] + self.I[-1] + raw[19], raw[20] = self.g + return raw + + def wait(self, n): + for _ in range(int(n)): + yield + + def set_pose(self, side, p, x, z): + p, x, z = np.array(p, float), np.array(x, float), np.array(z, float) + self.cart[side] = lambda t: (p, x, z) + + def current_pose(self, side): + c = self.cart[side] + if c is None or isinstance(c, tuple): + H = self.hand(side) + return H[:3, 3], H[:3, 0], H[:3, 2] + return c(self.t) + + def move(self, side, p1, x1, z1, n): + """Smooth Cartesian move from the current target to (p1, x1, z1) over n steps (non blocking).""" + p0, x0, z0 = [np.array(v, float) for v in self.current_pose(side)] + p1, x1, z1 = np.array(p1, float), np.array(x1, float), np.array(z1, float) + t0 = self.t + + def f(t): + a = smooth((t - t0) / max(1, n)) + x = (1 - a) * x0 + a * x1 + z = (1 - a) * z0 + a * z1 + return (1 - a) * p0 + a * p1, x / np.linalg.norm(x), z / np.linalg.norm(z) + self.cart[side] = f + + def joint(self, side, q): + self.cart[side] = ("joint", np.array(q, float)) + + STARTS = [np.array([sp, 0.2, 0, el, 0, 0, 0]) for sp in (-0.3, -0.9, -1.4) for el in (-0.6, 0.0, 0.6, 1.2)] + + def solve(self, side, p, x, z): + """IK for a goal pose: warm start from the current command plus multi-start.""" + B = self.base_frame() + cands = [self.q[side]] + [np.array([s0[0], s0[1] * side] + list(s0[2:])) for s0 in self.STARTS] + best = None + for s0 in cands: + qq, ee = ik(side, B, np.array(p, float), np.array(x, float), np.array(z, float), q0=s0, tip=GT, lam=0.01) + score = ee + 0.003 * np.linalg.norm(qq - self.q[side]) + if best is None or score < best[1]: + best = (qq, score, ee) + return best[0], best[2] + + def goto(self, side, p, x, z, n): + """Free-space move: joint interpolation to the IK solution of the goal, then hold the pose.""" + qg, e = self.solve(side, p, x, z) + q0 = self.q[side].copy() + t0 = self.t + p, x, z = np.array(p, float), np.array(x, float), np.array(z, float) + + def f(t): + a = smooth((t - t0) / max(1, n)) + if a >= 1.0: + self.cart[side] = lambda t: (p, x, z) + return (1 - a) * q0 + a * qg + self.cart[side] = ("jointf", f) + + def walk_to(self, x, maxn=200): + """Walk to pelvis x (station keeping continues afterwards).""" + self.hold_xy = (x, 0.0, 0.0) + self.arrived = False + n = 0 + yield from self.wait(3) + while not self.arrived and n < maxn: + yield + n += 1 + + def fingers(self, s): + lo = self.lo + return float(lo[10] if s > 0 else lo[19]) + + # -------------------------------------------------------------- vision + def image(self, cam): + return np.asarray(self.tools.image(cam), dtype=np.int32) + + @staticmethod + def detect_bar(im, side): + g = im.mean(2) + sat = im.max(2) - im.min(2) + m = (g < 130) & (sat < 25) + col = m[5:75].sum(0) + cols = np.where(col > 20)[0] + if len(cols) == 0: + return None + if side < 0: + cols = cols[::-1] + cl = [cols[0]] + for c in cols[1:]: + if abs(c - cl[-1]) <= 2: + cl.append(c) + else: + break + return (cl[0] + cl[-1]) / 2.0 + + # -------------------------------------------------------------- doors + def open_door(self, side): + s = side + gi = 0 if s > 0 else 1 + P = np.radians(45) + Y0 = np.radians(-15) * s + cam = "left_wrist" if s > 0 else "right_wrist" + bar = np.array([0.66, 0.025 * s, 1.25]) + x0, z0 = pitched(Y0, P) + back = 0.09 + self.move(s, bar - back * x0, x0, z0, 50) + yield from self.wait(65) + self.snap(f"door{s} pre") + stop = -0.005 + while back > stop: + u = self.detect_bar(self.image(cam), s) + C = cam_world(self.lo, s) + depth = max(0.04, float(np.dot(bar - C[:3, 3], C[:3, 0]))) + if u is not None and abs(u - 41.5) < 8 and back > 0.04: + bar = bar - (u - 41.5) / 66.0 * depth * C[:3, 1] * 0.7 + back = max(stop, back - 0.0075) + self.set_pose(s, bar - back * x0, x0, z0) + yield from self.wait(7) + yield from self.wait(15) + self.g[gi] = 1.0 + yield from self.wait(20) + self.snap(f"door{s} grasp") + hinge = np.array([0.70, 0.29 * s]) + v0 = bar[:2] - hinge + self.ki[s] = 0.0 + for deg in range(3, 61, 3): + ph = np.radians(deg) * s + c, sn = np.cos(ph), np.sin(ph) + v = np.array([c * v0[0] + sn * v0[1], -sn * v0[0] + c * v0[1]]) + x, z = pitched(Y0 - ph, P) + self.set_pose(s, [hinge[0] + v[0], hinge[1] + v[1], bar[2]], x, z) + yield from self.wait(8) + self.snap(f"door{s} pulled") + self.g[gi] = 0.0 + yield from self.wait(20) + p, x, z = self.current_pose(s) + self.move(s, p - 0.08 * x, x, z, 25) + yield from self.wait(25) + self.ki[s] = 0.03 + self.move(s, [0.36, 0.26 * s, 1.05], x, z, 30) + yield from self.wait(30) + + # ------------------------------------------------------------ cups + RH = 0.065 # handle grasp point distance from cup axis + ZG = 0.905 # grasp height + YAW_DEV = np.radians(15) + + def grasp_frame(self, s, A, h, pitch=0.0): + a = -h + G = np.array([A[0] + self.RH * h[0], A[1] + self.RH * h[1], self.ZG]) + yh = np.arctan2(a[1], a[0]) + yn = np.arctan2(G[1] - 0.15 * s, G[0] - 0.20) + d = (yh - yn + np.pi) % (2 * np.pi) - np.pi + yaw = float(yn + np.clip(d, -self.YAW_DEV, self.YAW_DEV)) + x, z = pitched(yaw, pitch) + return G, x, z + + def nat_dir(self, s, A): + yn = np.arctan2(A[1] - 0.15 * s, A[0] - 0.20) + return np.array([np.cos(yn), np.sin(yn)]) + + def view_pose(self, s, A): + a = self.nat_dir(s, A) + G, x, z = self.grasp_frame(s, A, -a, pitch=np.radians(20)) + xa = np.array([x[0], x[1], 0.0]) / np.linalg.norm(x[:2]) + return G - 0.12 * xa + np.array([0, 0, 0.06]), x, z + + def ready_pose(self, s): + x, z = pitched(-0.25 * s, np.radians(20)) + return np.array([0.48, 0.17 * s, 1.02]), x, z + + def measure_cup(self, s, A, h): + """Update cup axis / handle direction estimate from the wrist camera of arm s.""" + from cupvision import cup_measure, Z_BOT, R_CUP + cam = "left_wrist" if s > 0 else "right_wrist" + lo = self.lo + C = cam_world(lo, s) + uv, dist = project(C, s, np.array([A[0], A[1], 0.9])) + wp = 66.0 * 0.09 / max(0.05, dist[0]) + m = cup_measure(self.image(cam), uv[0, 0], wp) + if m is None or m["touch"] and m["w"] < 10: + return A, h, m + o, d = pix_ray(C, s, m["uc"], m["bot"] + 0.5) + if abs(d[2]) < 1e-3: + return A, h, m + p = o + (Z_BOT - o[2]) / d[2] * d + v = d[:2] / np.linalg.norm(d[:2]) + A_new = p[:2] + R_CUP * v + if not m["touch"]: + A = 0.3 * A + 0.7 * A_new + else: + o2, d2 = pix_ray(C, s, m["uc"], 42) + dd = d2[:2] / np.linalg.norm(d2[:2]) + w = A - o2[:2] + A = o2[:2] + dd * (w @ dd) + al = 0.0 + if m["hoff"] is not None: + if abs(m["hoff"]) >= 1.0: + al = np.sign(m["hoff"]) * np.radians(40) + else: + al = float(np.clip(np.arcsin(np.clip(0.7 * m["hoff"], -1, 1)), -0.7, 0.7)) + a = self.nat_dir(s, A) + r = np.array([a[1], -a[0]]) + hn = -np.cos(al) * a + np.sin(al) * r + h = 0.5 * h + 0.5 * hn + h = h / np.linalg.norm(h) + return A, h, m + + def center_on_handle(self, s, A, G, x): + """Shift the grasp point sideways so that it lines up with the handle seen by the wrist camera.""" + from cupvision import cup_measure + cam = "left_wrist" if s > 0 else "right_wrist" + C = cam_world(self.lo, s) + uvA, _ = project(C, s, np.array([A[0], A[1], 0.9])) + m = cup_measure(self.image(cam), uvA[0, 0]) + if self.DEBUG: + print("center", s, m) + if m is None or m["hu"] is None: + return G + uvG, dG = project(C, s, G) + o, d = pix_ray(C, s, m["hu"], uvG[0, 1]) + # point on the ray at the depth of G + P = o + d * (dG[0] / max(1e-3, d @ C[:3, 0])) + ly = np.array([-x[1], x[0], 0.0]) + ly /= np.linalg.norm(ly) + e = float(np.clip((P - G) @ ly, -0.03, 0.03)) + return G + 0.8 * e * ly + + B_STOP = 0.005 + U_HANDLE = 43.0 # wrist image column of a handle that is centred between the fingers + + def pregrasp_center(self, s, G, x): + from cupvision import pregrasp_handle + cam = "left_wrist" if s > 0 else "right_wrist" + C = cam_world(self.lo, s) + uvG, dG = project(C, s, G) + u = pregrasp_handle(self.image(cam), uvG[0, 0]) + if self.DEBUG: + print("pregrasp", s, u, uvG[0], dG) + if u is None: + return G + right = -C[:3, 1] + ly = np.array([-x[1], x[0], 0.0]) + ly /= np.linalg.norm(ly) + sgn = 1.0 if right @ ly > 0 else -1.0 + e = (u - self.U_HANDLE) / 66.0 * max(0.08, float(dG[0])) + e = float(np.clip(0.8 * e, -0.025, 0.025)) + return G + sgn * e * ly + + def grasp_cup(self, s, A, h=None, tries=2): + gi = 0 if s > 0 else 1 + if h is None: + h = -self.nat_dir(s, A) + for attempt in range(tries): + self.g[gi] = 0.0 + p, x, z = self.view_pose(s, A) + self.move(s, p, x, z, 45) + yield from self.wait(50) + for it in range(3): + A, h, m = self.measure_cup(s, A, h) + p, x, z = self.view_pose(s, A) + self.move(s, p, x, z, 15) + yield from self.wait(18) + self.snap(f"cup{s} view") + G, x, z = self.grasp_frame(s, A, h) + G = self.center_on_handle(s, A, G, x) + b = 0.12 + self.move(s, G - b * x, x, z, 25) + yield from self.wait(30) + for it in range(2): + G = self.pregrasp_center(s, G, x) + self.move(s, G - b * x, x, z, 12) + yield from self.wait(16) + self.snap(f"cup{s} pregrasp") + contact = False + while b > self.B_STOP: + b -= 0.01 + self.set_pose(s, G - b * x, x, z) + yield from self.wait(6) + if np.linalg.norm(self.hand(s)[:3, 3] - self.cmd_hand(s)) > 0.012 and b < 0.03: + contact = True + break + if contact: + b += 0.012 + self.set_pose(s, G - b * x, x, z) + yield from self.wait(10) + self.g[gi] = 1.0 + yield from self.wait(35) + p, xx, zz = self.current_pose(s) + self.move(s, p + np.array([0, 0, 0.05]), xx, zz, 50) + yield from self.wait(55) + f = self.fingers(s) + self.snap(f"cup{s} lifted b={b:.3f} fing {f:.4f}") + if f > -0.0175: + self.held[s] = True + self.cups[s] = (A, h) + return + # missed: open, back off and look again + self.g[gi] = 0.0 + p, xx, zz = self.current_pose(s) + self.move(s, p - 0.10 * xx, xx, zz, 25) + yield from self.wait(30) + + # ------------------------------------------------------------ placing + XPLACE = 0.75 + ZTOP = 1.29 + X_BACK = 0.10 # pelvis x while lifting the cups past the cabinet edge + X_WORK = 0.215 + + def arm_seq(self, s, steps): + """steps: list of (pos, xdir, zdir, n)""" + for p, x, z, n in steps: + self.move(s, p, x, z, n) + yield from self.wait(n + 5) + + def lower_and_release(self, s): + gi = 0 if s > 0 else 1 + yc = 0.10 * s + x0, z0 = pitched(0.0, 0.0) + self.move(s, [self.XPLACE, yc, 1.245], x0, z0, 50) + yield from self.wait(60) + zc = 1.245 + base_dev = self.hand(s)[2, 3] - self.cmd_hand(s)[2] + while zc > 1.225: + zc -= 0.004 + self.set_pose(s, [self.XPLACE, yc, zc], x0, z0) + yield from self.wait(6) + dev = self.hand(s)[2, 3] - self.cmd_hand(s)[2] + if dev - base_dev > 0.006: + break + yield from self.wait(10) + self.snap(f"place{s} down z={zc:.3f}") + self.g[gi] = 0.0 + yield from self.wait(30) + p, x, z = self.current_pose(s) + self.move(s, p - np.array([0.10, 0, -0.005]), x, z, 45) + yield from self.wait(50) + self.snap(f"place{s} released") + x45, z45 = pitched(0.0, np.radians(45)) + yield from self.arm_seq(s, [([0.55, 0.15 * s, 1.15], x45, z45, 40), + ([0.42, 0.24 * s, 0.95], x45, z45, 40)]) + self.joint(s, [0.0, 0.25 * s, 0, 0.3, 0, 0, 0]) + + def wait_reach(self, sides, zmin, maxn=60): + n = 0 + while n < maxn and any(self.hand(s)[2, 3] < zmin for s in sides): + yield + n += 1 + + def place_cups(self, sides): + x0, z0 = pitched(0.0, 0.0) + gens = [] + for s in sides: + p, x, z = self.current_pose(s) + yaw = float(np.arctan2(x[1], x[0])) + xg, zg = pitched(yaw, 0.0) + gens.append(self.arm_seq(s, [([0.50, p[1], p[2] + 0.02], xg, zg, 150)])) + yield from par(*gens) + self.pitch = 0.0 + self.height = 0.79 + yield from self.walk_to(self.X_BACK) + self.snap("place back") + gens = [self.arm_seq(s, [([0.53, 0.10 * s, 1.10], x0, z0, 70), + ([0.53, 0.10 * s, self.ZTOP], x0, z0, 80)]) for s in sides] + yield from par(*gens) + yield from self.wait_reach(sides, self.ZTOP - 0.025) + for s in sides: + self.move(s, [0.66, 0.10 * s, self.ZTOP], x0, z0, 40) + yield from self.wait(45) + self.snap("place up") + yield from self.walk_to(self.X_WORK) + for s in sides: + self.move(s, [self.XPLACE, 0.10 * s, self.ZTOP], x0, z0, 40) + yield from self.wait(50) + self.snap("place in") + yield from par(*[self.lower_and_release(s) for s in sides]) + for s in sides: + self.held[s] = False + self.height = 0.74 + + # ------------------------------------------------------------ main + def coarse_cups(self): + from cupvision import perceive + cups = perceive(self.lo, self.image("left_wrist"), self.image("right_wrist")) + cups = [c for c in cups if 0.6 < c["xy"][0] < 1.0 and abs(c["xy"][1]) < 0.35] + cups.sort(key=lambda c: -c["xy"][1]) + if len(cups) > 2: + cups = sorted(cups, key=lambda c: -c["n"])[:2] + cups.sort(key=lambda c: -c["xy"][1]) + out = {} + if len(cups) == 2: + out[1], out[-1] = cups[0]["xy"], cups[1]["xy"] + elif len(cups) == 1: + c = cups[0]["xy"] + if c[1] >= 0: + out[1], out[-1] = c, np.array([0.8, min(-0.08, c[1] - 0.15)]) + else: + out[-1], out[1] = c, np.array([0.8, max(0.08, c[1] + 0.15)]) + else: + out[1], out[-1] = np.array([0.8, 0.1]), np.array([0.8, -0.1]) + return out + + def _main(self): + self.hold_xy = (0.215, 0.0, 0.0) + for s in (1, -1): + self.goto(s, *self.ready_pose(s), 50) + yield from self.wait(60) + self.snap("ready") + cups = self.coarse_cups() + if self.DEBUG: + print("coarse cups", cups) + yield from par(self.open_door(1), self.open_door(-1)) + self.snap("doors") + self.hold_xy = (0.215, 0.0, 0.0) + self.pitch = 0.15 + for s in (1, -1): + self.goto(s, *self.ready_pose(s), 40) + yield from self.wait(45) + yield from self.walk_to(self.X_WORK, maxn=150) + yield from par(*[self.grasp_cup(s, np.array(cups[s], float)) for s in (1, -1)]) + sides = [s for s in (1, -1) if self.held[s]] + for s in (1, -1): + if not self.held[s]: + self.joint(s, [0.0, 0.25 * s, 0, 0.3, 0, 0, 0]) + if sides: + yield from self.place_cups(sides) + self.snap("end") + while True: + yield + + def act(self, obs, tools): + self.obs = obs + self.tools = tools + try: + next(self.gen) + except StopIteration: + pass + raw = self._action() + self.t += 1 + return np.asarray(raw, dtype=np.float32) diff --git a/policies/put_cups/opus-s3/episodes.csv b/policies/put_cups/opus-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f07188c1e36ce62841ee9aa30874cd299fb4de7e --- /dev/null +++ b/policies/put_cups/opus-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/opus-s3/g1kin.py b/policies/put_cups/opus-s3/g1kin.py new file mode 100644 index 0000000000000000000000000000000000000000..8c872753b4ae357dde8064100ded9a9c256f9d16 --- /dev/null +++ b/policies/put_cups/opus-s3/g1kin.py @@ -0,0 +1,185 @@ +"""Kinematics helpers for the G1 policy: arm FK/IK (approximate URDF numbers), +wrist-camera model (fitted from the robot's own images), base pose control. + +World frame model: pelvis at (x, y, z, yaw) from low_dim_obs, pitched by PPITCH, +then the waist joints (also from low_dim_obs), then the arm chain.""" +import numpy as np +from scipy.optimize import least_squares + +PPITCH = -0.155 # pelvis pitch (rad, + = lean forward) +CAM_F = 82.1 # wrist camera focal length, px (84x84 image) +CAM_D = 0.764 # wrist camera pitched down relative to the gripper axis, rad +CAM_OFF = (0.117, 0.0, 0.0665) # camera position in the wrist-yaw frame + +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 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 wrap(a): + return (a + np.pi) % (2 * np.pi) - np.pi + + +def torso_M(waist): + wy, wr, wp = waist + M = T(rz(wy)) + M = M @ T(rx(wr), (-0.0039635, 0, 0.035)) + return M @ T(ry(wp), (0, 0, 0.019)) + + +def arm_frames(q, side, waist): + """Shoulder, elbow and wrist-yaw frames in the pelvis frame.""" + s = 1 if side == 'L' else -1 + M = torso_M(waist) + M = M @ T(rx(s * 0.27931), (0.0039563, s * 0.10022, 0.23778)) @ T(ry(q[0])) + sh = M.copy() + M = M @ T(rx(-s * 0.27925), (0, s * 0.038, -0.013831)) @ T(rx(q[1])) + M = M @ T(None, (0, s * 0.00624, -0.1032)) @ T(rz(q[2])) + M = M @ T(None, (0.015783, 0, -0.080518)) @ T(ry(q[3])) + el = M.copy() + M = M @ T(None, (0.100, s * 0.00188791, -0.010)) @ T(rx(q[4])) + M = M @ T(None, (0.038, 0, 0)) @ T(ry(q[5])) + M = M @ T(None, (0.046, 0, 0)) @ T(rz(q[6])) + return sh, el, M + + +def base_M(obsq): + return T(rz(obsq[24]) @ ry(PPITCH), (obsq[21], obsq[22], obsq[23])) + + +def arm_q(obsq, side): + return obsq[3:10] if side == 'L' else obsq[12:19] + + +def wrist_world(obsq, side, qa=None): + qa = arm_q(obsq, side) if qa is None else qa + return base_M(obsq) @ arm_frames(qa, side, obsq[0:3])[2] + + +def tool_world(obsq, side, L, qa=None): + return wrist_world(obsq, side, qa) @ T(None, (L, 0, 0)) + + +def cam_M(obsq, side, qa=None): + return wrist_world(obsq, side, qa) @ T(ry(CAM_D), CAM_OFF) + + +def project(M, P): + P = np.atleast_2d(np.asarray(P, float)) + Pc = (np.linalg.inv(M) @ np.c_[P, np.ones(len(P))].T)[:3].T + u = 41.5 - CAM_F * Pc[:, 1] / Pc[:, 0] + v = 41.5 - CAM_F * Pc[:, 2] / Pc[:, 0] + return u, v, Pc[:, 0] + + +def pixel_ray(M, u, v): + d = np.array([1.0, -(u - 41.5) / CAM_F, -(v - 41.5) / CAM_F]) + d = M[:3, :3] @ d + return M[:3, 3], d / np.linalg.norm(d) + + +def ray_plane_z(M, u, v, z): + o, d = pixel_ray(M, u, v) + t = (z - o[2]) / d[2] + return o + t * d + + +def limits(side): + lo, hi = LO.copy(), HI.copy() + if side == 'R': + for k in (1, 2, 4, 6): + lo[k], hi[k] = -HI[k], -LO[k] + return lo, hi + + +def ik(side, pos_w, xdir_w, q0, obsq, L=0.20, ydir_z=0.0, w_ori=0.3, + w_reg=0.02, qnom=None, waist=None, wreg_vec=None): + """Arm joints so that the tool point (L along gripper x) reaches pos_w (world), + gripper x axis along xdir_w, finger axis (gripper y) with world z component ydir_z.""" + B = base_M(obsq) + W = torso_M(obsq[0:3] if waist is None else waist) # noqa: F841 (used via arm_frames) + wst = obsq[0:3] if waist is None else waist + Binv = np.linalg.inv(B) + p = (Binv @ np.r_[np.asarray(pos_w, float), 1])[:3] + xd = B[:3, :3].T @ np.asarray(xdir_w, float) + xd = xd / np.linalg.norm(xd) + zw = B[:3, :3].T @ np.array([0, 0, 1.0]) + lo, hi = limits(side) + q0 = np.clip(np.asarray(q0, float), lo + 1e-4, hi - 1e-4) + qn = q0 if qnom is None else np.asarray(qnom, float) + + def res(q): + M = arm_frames(q, side, wst)[2] @ T(None, (L, 0, 0)) + r = list(M[:3, 3] - p) + r += list(w_ori * (M[:3, 0] - xd)) + r.append(w_ori * (M[:3, 1] @ zw - ydir_z)) + r += list((w_reg if wreg_vec is None else np.asarray(wreg_vec)) * (q - qn)) + return r + + s = least_squares(res, q0, bounds=(lo, hi), xtol=1e-7, ftol=1e-9, max_nfev=300) + M = arm_frames(s.x, side, wst)[2] @ T(None, (L, 0, 0)) + return s.x, float(np.linalg.norm(M[:3, 3] - p)) + + +class BaseCtl: + """Hysteresis position controller for the walking base.""" + + def __init__(self, target, start_tol=0.03, stop_tol=0.012, ystart=0.05, ystop=0.015): + self.target = np.array(target, float) + self.active = False + self.yactive = False + self.start_tol, self.stop_tol = start_tol, stop_tol + self.ystart, self.ystop = ystart, ystop + + def __call__(self, q, vmax=0.25): + x, y, yaw = q[21], q[22], q[24] + dx, dy = self.target[0] - x, self.target[1] - y + c, s = np.cos(yaw), np.sin(yaw) + ex, ey = c * dx + s * dy, -s * dx + c * dy + eyaw = wrap(self.target[2] - yaw) + n = np.hypot(ex, ey) + if n > self.start_tol: + self.active = True + if n < self.stop_tol: + self.active = False + vx = vy = 0.0 + if self.active: + v = np.array([ex, ey]) * 2.0 + sp = np.linalg.norm(v) + if sp > vmax: + v *= vmax / sp + elif sp < 0.08: + v *= 0.08 / max(sp, 1e-9) + vx, vy = v + if abs(eyaw) > self.ystart: + self.yactive = True + if abs(eyaw) < self.ystop: + self.yactive = False + wz = 0.0 + if self.yactive: + wz = float(np.clip(2.0 * eyaw, -0.4, 0.4)) + if abs(wz) < 0.12: + wz = 0.12 * np.sign(wz) + return float(vx), float(vy), wz diff --git a/policies/put_cups/opus-s3/policy.py b/policies/put_cups/opus-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..7c71dc20bc94546802ddfbed12bfa06b80d4dc25 --- /dev/null +++ b/policies/put_cups/opus-s3/policy.py @@ -0,0 +1,728 @@ +"""Put the cups from the counter into the wall cabinet (Unitree G1, BiGym kitchen). + +Hand-written control: a scripted sequence of phases driven by proprioception +(arm FK/IK with the approximate G1 URDF kinematics) and the robot's own cameras +(colour segmentation of handles / cups, projected with a fitted pinhole model). +""" +import os +import sys + +import numpy as np + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import g1kin as K # noqa: E402 +import vision as V # noqa: E402 + +DEBUG = {} + + +def _noop(*a, **k): + pass + + +def mirror(q): + q = list(q) + for k in (1, 2, 4, 6): + q[k] = -q[k] + return np.array(q, float) + + +def smooth(f): + f = min(max(f, 0.0), 1.0) + return f * f * (3 - 2 * f) + + +class Policy: + def reset(self, obs, tools): + self.tools = tools + self.obs = obs + a = np.asarray(tools.hold_action(), dtype=np.float64) + self.a = a + self.qcmd = {'L': a[5:12].copy(), 'R': a[12:19].copy()} + self.integ = {'L': np.zeros(7), 'R': np.zeros(7)} + self.ki = {'L': 0.0, 'R': 0.0} + self.ilim = {'L': 0.25, 'R': 0.25} + self.grip = {'L': 0.0, 'R': 0.0} + self.pitch = 0.0 + self.height = 0.74 + q = obs['low_dim_obs'] + self.home = np.array([q[21], q[22], q[24]], float) + self.base = K.BaseCtl((q[21], q[22], q[24])) + self.base_on = True + self.log = [] + self.gen = self.script() + self.done = False + + # ------------------------------------------------------------------ utils + @property + def q(self): + return self.obs['low_dim_obs'] + + def qarm(self, side): + return self.q[3:10] if side == 'L' else self.q[12:19] + + def mark(self, name): + self.log.append((int(self.obs['t']), name)) + cb = DEBUG.get('mark') + if cb: + cb(self, name) + + def act(self, obs, tools): + self.obs = obs + if not self.done: + try: + next(self.gen) + except StopIteration: + self.done = True + a = self.a + for side, sl in (('L', slice(5, 12)), ('R', slice(12, 19))): + err = self.qcmd[side] - self.qarm(side) + self.integ[side] = np.clip(self.integ[side] + self.ki[side] * err, -self.ilim[side], self.ilim[side]) + lo, hi = K.limits(side) + a[sl] = np.clip(self.qcmd[side] + self.integ[side], lo, hi) + a[19], a[20] = self.grip['L'], self.grip['R'] + a[2] = self.height + a[4] = self.pitch + if self.base_on: + a[0], a[1], a[3] = self.base(self.q) + else: + a[0] = a[1] = a[3] = 0.0 + return a.astype(np.float32) + + # ------------------------------------------------------------ primitives + def wait(self, n): + for _ in range(n): + yield + + def joints(self, n, L=None, R=None): + q0 = {s: self.qcmd[s].copy() for s in 'LR'} + goal = {'L': L, 'R': R} + for i in range(n): + f = smooth((i + 1) / n) + for s in 'LR': + if goal[s] is not None: + self.qcmd[s] = q0[s] + (np.asarray(goal[s]) - q0[s]) * f + yield + + WREG = np.array([0.01, 0.01, 0.3, 0.01, 0.3, 0.01, 0.05]) + + def solve(self, side, pos, xdir, qnom, L=0.18, ydz=0.0, wreg=None): + qs, err = K.ik(side, pos, xdir, qnom, self.q, L=L, qnom=qnom, + wreg_vec=self.WREG if wreg is None else wreg, ydir_z=ydz) + return qs, err + + def reach(self, side, pos, xdir, qnom, n=60, L=0.18, settle=40, tol=0.008, ydz=0.0): + """Move the tool point to pos (world) with joint interpolation, then + correct the remaining Cartesian error from measured joints.""" + qs, err = self.solve(side, pos, xdir, qnom, L, ydz) + yield from self.joints(n, **{side: qs}) + tgt = np.array(pos, float) + for k in range(settle): + yield + if k % 10 == 9: + cur = K.tool_world(self.q, side, L)[:3, 3] + e = np.asarray(pos) - cur + if np.linalg.norm(e) < tol: + break + tgt = np.asarray(pos) + np.clip(tgt + 0.8 * e - np.asarray(pos), -0.03, 0.03) + qs, _ = self.solve(side, tgt, xdir, self.qcmd[side], L, ydz) + self.qcmd[side] = qs + + # ---------------------------------------------------------------- script + def script(self): + self.mark('start') + self.grip = {'L': 0.0, 'R': 0.0} + yield from self.wait(1) + yield from self.stage_raise() + if DEBUG.get('cups_only'): + yield from self.joints(80, L=self.LOOK_L, R=self.LOOK_R) + yield from self.stage_cups() + self.mark('end') + yield from self.stage_walk(0.30, self.HANDLE['L'][1] - 0.06) + self.mark('walked') + yield from self.joints(40, R=self.LOOK_R) + self.mark('look0') + yield from self.stage_door('L') + self.mark('door_L_after') + if DEBUG.get('only_L'): + self.mark('end') + yield from self.retract('L', self.LOOK_L) + yield from self.stage_walk(0.30, self.HANDLE['R'][1] + 0.06) + self.mark('walked_R') + yield from self.stage_door('R') + yield from self.retract('R', self.LOOK_R) + self.mark('doors_done') + if DEBUG.get('doors_only'): + self.mark('end') + yield from self.stage_cups() + self.mark('end') + while True: + yield + + # ------------------------------------------------------------------ cups + CUP_DX = 0.033 # head-camera bias correction (x) + CUP_GRASP_Z = 1.03 + CUP_FILL = 0.6 + CARRY_Z = 1.37 + RELEASE_Z = 1.335 + PLACE_REACH = 0.42 + CUP_EXTRA = 0.02 + CUP_YOFF = {'L': 0.0, 'R': -0.015} + PLACE_X = 0.80 + PLACE_DY = 0.06 + FLOOR_Z = 1.245 + + def stage_cups(self): + say = DEBUG.get('print', _noop) + yield from self.stage_walk(0.32, self.CAB_Y) + yield from self.wait(10) + cups = V.head_cups(self.tools.image('head'), self.q) + self.mark('cups_seen') + cups = [c for c in cups if c['n'] >= 60] + for c in cups: + c['x'] += self.CUP_DX + say('cups', cups) + if not cups: + return + cups.sort(key=lambda c: -c['y']) + if len(cups) < 2: + side = 'L' if cups[0]['y'] > self.CAB_Y else 'R' + cups = [cups[0], None] if side == 'L' else [None, cups[0]] + cL, cR = cups[0], cups[-1] + xs = [c['x'] for c in (cL, cR) if c is not None] + ys = [c['y'] for c in (cL, cR) if c is not None] + by = float(np.mean(ys)) if len(ys) == 2 else (ys[0] - 0.10 if cL is not None else ys[0] + 0.10) + yield from self.stage_walk(min(xs) - 0.47, by) + gens = [] + if cL is not None: + gens.append(self.grasp_cup('L', cL)) + if cR is not None: + gens.append(self.grasp_cup('R', cR)) + yield from self.parallel(gens) + self.mark('cups_lifted') + if DEBUG.get('stop_lift'): + return + self.base_on = True + yield from self.stage_walk(0.34, self.CAB_Y) + gens = [] + if cL is not None: + gens.append(self.place_cup('L', +1)) + if cR is not None: + gens.append(self.place_cup('R', -1)) + yield from self.parallel(gens) + self.mark('cups_placed') + + def parallel(self, gens): + gens = list(gens) + while gens: + alive = [] + for g in gens: + try: + next(g) + alive.append(g) + except StopIteration: + pass + gens = alive + if gens: + yield + + def grasp_cup(self, side, c): + say = DEBUG.get('print', _noop) + cam = 'left_wrist' if side == 'L' else 'right_wrist' + fx = np.array([1.0, 0, 0]) + qn = np.array([-0.5, 0.1, 0.1, -0.5, 0, 1.0, 0.2]) + qn = qn if side == 'L' else mirror(qn) + self.grip[side] = 0.0 + self.ki[side] = 0.0 + self.integ[side][:] = 0.0 + z = self.CUP_GRASP_Z + pre = np.array([c['x'] - 0.17, c['y'], z]) + hi = pre + np.array([-0.05, 0, 0.12]) + yield from self.reach(side, hi, fx, qn, n=40, settle=0) + yield from self.reach(side, pre, fx, self.qcmd[side], n=35, settle=15) + self.mark('cup_pre_' + side) + for it in range(4): + yield from self.wait(10) + bl = V.wrist_cup(self.tools.image(cam)) + if bl is None: + say('no cup', side); continue + du = bl['cu'] - 41.5 + say('cup align', side, it, bl, 'du %.1f' % du) + if abs(du) < 2.0: + break + dy = -0.8 * du * 0.16 / K.CAM_F + tool = K.tool_world(self.q, side, 0.18) + pre = pre + np.clip(dy, -0.03, 0.03) * tool[:3, 1] + qs, _ = self.solve(side, pre, fx, self.qcmd[side]) + yield from self.joints(12, **{side: qs}) + pre = pre + np.array([0.0, self.CUP_YOFF[side], 0.0]) + start = pre.copy() + lag0 = (K.tool_world(self.q, side, 0.18, self.qcmd[side])[:3, 3] - K.tool_world(self.q, side, 0.18)[:3, 3])[0] + n = 140 + for i in range(n): + pre = start + np.array([0.22 * (i + 1) / n, 0, 0]) + if i % 3 == 0: + qs, _ = self.solve(side, pre, fx, self.qcmd[side]) + self.qcmd[side] = qs + yield + tool = K.tool_world(self.q, side, 0.18)[:3, 3] + lag = (K.tool_world(self.q, side, 0.18, self.qcmd[side])[:3, 3] - tool)[0] + if i > 10 and lag - lag0 > 0.015: + say('cup contact', side, i) + break + if i % 3 == 2: + m = V.cup_mask(self.tools.image(cam)) + fill = m[5:30, 8:76].mean() + if fill > self.CUP_FILL: + say('cup fill', side, i, fill) + break + # finish the last bit blind: the handle sits under the camera + p0 = pre.copy() + yield from self.line(side, p0, p0 + np.array([self.CUP_EXTRA, 0, 0]), 20, fx) + self.grip[side] = 1.0 + yield from self.wait(25) + self.mark('cup_closed_' + side) + say('held', side, self.q[50:52]) + g = K.tool_world(self.q, side, 0.18, self.qcmd[side])[:3, 3] + self.ki[side] = 0.04 + self.ilim[side] = 0.7 + up = np.array([g[0], g[1], 1.06]) + yield from self.cline(side, g, up, 50) + self.mark('cup_up_' + side) + hi = np.array([self.q[21] + 0.26, g[1], self.CARRY_Z]) + yield from self.cline(side, up, hi, 150) + yield from self.wait(8) + + QN_UP = np.array([-2.9, 0.45, 0.1, 1.6, 0.0, 1.3, 0.0]) + + def cline(self, side, p0, p1, n): + """Straight tool path with the gripper kept horizontal / level (stiff + orientation), each IK step regularised to the previous solution.""" + p0, p1 = np.asarray(p0, float), np.asarray(p1, float) + wv = np.full(7, 0.01) + for i in range(n): + if i % 2 == 0: + p = p0 + (p1 - p0) * smooth((i + 2) / n) + qs, _ = K.ik(side, p, (1, 0, 0), self.qcmd[side], self.q, L=0.18, + qnom=self.qcmd[side], wreg_vec=wv, w_ori=1.0) + self.qcmd[side] = qs + yield + + def line(self, side, p0, p1, n, xd): + p0, p1 = np.asarray(p0, float), np.asarray(p1, float) + for i in range(n): + if i % 2 == 0: + p = p0 + (p1 - p0) * smooth((i + 2) / n) + qs, _ = self.solve(side, p, xd, self.qcmd[side]) + self.qcmd[side] = qs + yield + + def place_cup(self, side, slot): + fx = np.array([1.0, 0, 0]) + yp = self.CAB_Y + slot * self.PLACE_DY + cur = K.tool_world(self.q, side, 0.18, self.qcmd[side])[:3, 3] + a = np.array([cur[0], yp, self.CARRY_Z]) + yield from self.cline(side, cur, a, 40) + tgt = np.array([self.q[21] + self.PLACE_REACH, yp, self.CARRY_Z]) + yield from self.cline(side, a, tgt, 100) + yield from self.wait(8) + self.mark('cup_in_' + side) + down = tgt.copy() + down[2] = self.RELEASE_Z + yield from self.cline(side, tgt, down, 40) + yield from self.wait(10) + self.grip[side] = 0.0 + yield from self.wait(20) + self.mark('cup_placed_' + side) + out = down + np.array([-0.18, 0, 0.02]) + yield from self.cline(side, down, out, 50) + + def look_pose(self, side): + """Development helper: point a wrist camera at the cabinet front.""" + s = 1 if side == 'L' else -1 + p = self.q[21:24] + pos = np.array([p[0] + 0.12, s * 0.22 + p[1], 1.10]) + xd = np.array([0.45, -s * 0.35, 0.82]) + qn = self.W_UP if side == 'L' else mirror(self.W_UP) + yield from self.reach(side, pos, xd, qn, n=80, settle=20) + self.mark('look_' + side) + + QN_HIGH = np.array([-2.0, 0.15, 0.1, 0.0, 0.0, 1.4, 0.0]) + W_UP = np.array([-1.6, 0.2, 0.8, -1.0, 0, 1.4, 0]) + LOOK = np.array([0.3, 0.0, 0.0, -0.8, 0.0, -0.7, 0.0]) + LOOK_R = np.array([0.438, -0.61, 0.456, -0.456, 0.039, -1.614, -0.27]) + LOOK_L = np.array([0.486, 0.635, -0.282, -0.464, -0.309, -1.614, 0.1]) + + def retract(self, side, qend, back=0.08): + t = K.tool_world(self.q, side, 0.18) + p = t[:3, 3] - np.array([back, 0, 0]) + qs, _ = self.solve(side, p, t[:3, 0], self.qcmd[side]) + yield from self.joints(25, **{side: qs}) + p[2] = 1.08 + qs, _ = self.solve(side, p, t[:3, 0], self.qcmd[side]) + yield from self.joints(30, **{side: qs}) + yield from self.joints(50, **{side: qend}) + + def stage_raise(self): + yield from self.joints(90, L=self.W_UP, R=mirror(self.W_UP)) + yield from self.wait(5) + + def stage_walk(self, x=0.31, y=0.0): + self.base.target[0] = x + self.base.target[1] = y + for i in range(300): + yield + if i > 40 and not self.base.active and not self.base.yactive: + break + + HANDLE = {'L': (0.62, 0.025, 1.30), 'R': (0.62, -0.065, 1.30)} + CAB_Y = -0.02 + DOOR_TILT = 0.76 + DOOR_ARC = 45.0 + PULL0 = 0.03 + PULL_WALK = 0.14 # degrees the door is pulled open + BAR_W = 0.015 # handle bar thickness (m), sets the depth from apparent width + BAR_DEPTH = 0.08 + BAR_WPX = 14 # apparent bar width (px) when it sits between the pads # camera-to-bar distance with the bar between the finger pads + + def find_bar(self, side, hy): + cam = 'left_wrist' if side == 'L' else 'right_wrist' + im = self.tools.image(cam) + M = K.cam_M(self.q, side) + best = None + for b in V.dark_bars(im): + # median row width >= 3 px (handles), rejects thin seams + rows = np.unique(b['ys']) + wid = np.median([np.sum(b['ys'] == r) for r in rows]) + if wid < 3 or len(rows) < 8: + continue + w = V.bar_world(b, M, 0.66) + if w is None: + continue + # bar column near the image centre row band + sel = np.abs(b['ys'] - 41.5) < 12 + cu = b['xs'][sel].mean() if sel.sum() > 3 else b['cu'] + c = abs(w['y'] - hy) + if best is None or c < best[0]: + best = (c, dict(w, cu=cu, n=b['n'])) + return None if best is None else best[1] + + def stage_doors(self, side='L'): + """Grab both (adjacent) door handles with one gripper, pull both doors + open a little, then wedge them open with the closed gripper.""" + say = DEBUG.get('print', _noop) + tl = self.DOOR_TILT + xd = np.array([np.cos(tl), 0, np.sin(tl)]) + qn = np.array([-1.6, 0.0, 0.1, -0.4, 0, 1.2, 0.3]) + qn = qn if side == 'L' else mirror(qn) + self.ki[side] = 0.05 + cam = 'left_wrist' if side == 'L' else 'right_wrist' + pre = np.array([0.49, self.CAB_Y, 1.30]) + yield from self.reach(side, pre, xd, qn, n=100, settle=40) + self.base_on = False + yield from self.wait(40) + self.mark('doors_pre') + + def look(): + M = K.cam_M(self.q, side) + bars = [b for b in V.handle_bars(self.tools.image(cam), M) + if abs(b['cu'] - 41.5) < 42 and abs(b['y'] - self.CAB_Y) < 0.07 + and b['zmax'] - b['zmin'] > 0.05] + bars.sort(key=lambda b: -b['y']) + return bars + + def target_u(bars): + if len(bars) >= 2: + b0, b1 = bars[0], bars[-1] + return 0.5 * (b0['cu'] + b1['cu']), 0.5 * (b0['width'] + b1['width']) + b = bars[0] + depth = K.CAM_F * self.BAR_W / max(b['width'], 3) + off = 0.022 * K.CAM_F / depth + return (b['cu'] + off if b['y'] > self.CAB_Y else b['cu'] - off), b['width'] + + for it in range(8): + bars = look() + if not bars: + say('no bars'); yield from self.wait(10); continue + u, w = target_u(bars) + depth = K.CAM_F * self.BAR_W / max(w, 3) + du = u - 41.5 + say('align2', it, len(bars), [(round(b['cu'], 1), round(b['y'], 3)) for b in bars], 'du %.1f' % du) + if DEBUG.get('servo_marks'): + self.mark('align%d' % it) + if abs(du) < 2.0: + break + tool = K.tool_world(self.q, side, 0.18) + dy = -0.8 * du * depth / K.CAM_F + pre = pre + np.clip(dy, -0.04, 0.04) * tool[:3, 1] + qs, _ = self.solve(side, pre, xd, self.qcmd[side]) + yield from self.joints(15, **{side: qs}) + yield from self.wait(12) + # advance in +x until contact + start = pre.copy() + n = 100 + for i in range(n): + pre = start + np.array([0.12 * (i + 1) / n, 0, 0]) + if i % 3 == 0: + qs, _ = self.solve(side, pre, xd, self.qcmd[side]) + self.qcmd[side] = qs + yield + tool = K.tool_world(self.q, side, 0.18)[:3, 3] + lag = (K.tool_world(self.q, side, 0.18, self.qcmd[side])[:3, 3] - tool)[0] + if lag > 0.02: + say('contact', i) + break + yield from self.wait(10) + self.mark('doors_at') + self.grip[side] = 1.0 + yield from self.wait(30) + self.mark('doors_closed') + g = K.tool_world(self.q, side, 0.18)[:3, 3] + n = 150 + for i in range(n): + p = g + np.array([-0.10 * smooth((i + 1) / n), 0, 0]) + if i % 3 == 0: + qs, _ = self.solve(side, p, xd, self.qcmd[side]) + self.qcmd[side] = qs + yield + self.mark('doors_pulled') + self.grip[side] = 0.0 + yield from self.wait(25) + self.mark('doors_released') + self.base_on = True + + def stage_door(self, side): + hx, hy, hz = self.HANDLE[side] + tl = self.DOOR_TILT + xd = np.array([np.cos(tl), 0, np.sin(tl)]) + qn = np.array([-1.6, 0.0, 0.1, -0.4, 0, 1.2, 0.3]) + qn = qn if side == 'L' else mirror(qn) + self.ki[side] = 0.05 + pre = np.array([hx - 0.13, hy, hz]) + yield from self.reach(side, pre, xd, qn, n=70, settle=20) + self.mark('door_pre_' + side) + self.base_on = False + # visual servo: centre the handle bar between the fingers and advance + # until its apparent width says it is at the finger pads + cam = 'left_wrist' if side == 'L' else 'right_wrist' + yield from self.wait(15) + track = None + s = 1 if side == 'L' else -1 + say = DEBUG.get('print', _noop) + hy0 = hy + + def look(track): + M = K.cam_M(self.q, side) + bars = [b for b in V.handle_bars(self.tools.image(cam), M) + if abs(b['cu'] - 41.5) < 40 and abs(b['y'] - self.CAB_Y) < 0.12 + and b['zmax'] - b['zmin'] > 0.05 and b['width'] >= 4] + if not bars: + return None + return min(bars, key=lambda b: b['cu']) if side == 'L' else max(bars, key=lambda b: b['cu']) + + # 1) lateral / vertical alignment at a distance + for it in range(5): + b = look(None) + if b is None: + say('no bar') + if DEBUG.get('servo_marks'): + self.mark('nobar%d' % it) + yield from self.wait(10) + continue + track = b['cu'] + depth = K.CAM_F * self.BAR_W / max(b['width'], 3) + du = b['cu'] - 41.5 + dz = 0.0 + if b['top'] > 15: + dz = -0.01 * min(3.0, (b['top'] - 15) / 10) + elif b['bot'] < 75: + dz = 0.01 * min(3.0, (75 - b['bot']) / 10) + say('align', it, b, 'du %.1f depth %.3f dz %.3f' % (du, depth, dz)) + if DEBUG.get('servo_marks'): + self.mark('align%d' % it) + if abs(du) < 2.5 and dz == 0.0: + break + tool = K.tool_world(self.q, side, 0.18) + dy = -0.8 * du * depth / K.CAM_F + pre = pre + np.clip(dy, -0.04, 0.04) * tool[:3, 1] + np.array([0, 0, dz]) + qs, _ = self.solve(side, pre, xd, self.qcmd[side]) + yield from self.joints(15, **{side: qs}) + yield from self.wait(12) + track = None if abs(du) > 20 else track + # 2) advance straight in +x until the bar is at the pads (or contact) + yield from self.wait(8) + start = pre.copy() + px0 = self.q[21] + lag0 = (K.tool_world(self.q, side, 0.18, self.qcmd[side])[:3, 3] - K.tool_world(self.q, side, 0.18)[:3, 3])[0] + n = 100 + for i in range(n): + pre = start + np.array([0.12 * (i + 1) / n, 0, 0]) + if i % 3 == 0: + qs, _ = self.solve(side, pre, xd, self.qcmd[side]) + self.qcmd[side] = qs + yield + tool = K.tool_world(self.q, side, 0.18)[:3, 3] + lag = (K.tool_world(self.q, side, 0.18, self.qcmd[side])[:3, 3] - tool)[0] + if lag - lag0 > 0.015 or px0 - self.q[21] > 0.02: + say('contact at', i, 'lag %.3f dpx %.3f' % (lag, px0 - self.q[21])) + break + if i % 4 == 3: + b = look(None) + if b is not None and b['width'] >= self.BAR_WPX: + say('bar wide at', i, b['width']) + break + yield from self.wait(15) + b = look(None) + say('at', b) + self.mark('door_at_' + side) + hx, hy, hz = pre + self.grip[side] = 1.0 + yield from self.wait(20) + self.mark('door_closed_' + side) + # pull along the door arc, hinge placed relative to the measured grasp + s = 1 if side == 'L' else -1 + g = K.tool_world(self.q, side, 0.18)[:3, 3] + hz = g[2] + n = 60 + for i in range(n): + p = g + np.array([-self.PULL0 * smooth((i + 1) / n), 0, 0]) + if i % 3 == 0: + qs, _ = self.solve(side, p, xd, self.qcmd[side]) + self.qcmd[side] = qs + if DEBUG.get('servo_marks') and i % 50 == 0: + self.mark('pull%d' % i) + yield + self.mark('door_pulled_' + side) + if DEBUG.get('sweep'): + # release, back off, then sweep the door open from the inside + self.grip[side] = 0.0 + yield from self.wait(15) + p = K.tool_world(self.q, side, 0.18)[:3, 3] + p[0] = 0.48 + qs, _ = self.solve(side, p, xd, self.qcmd[side]) + yield from self.joints(30, **{side: qs}) + self.grip[side] = 1.0 + fx = np.array([1.0, 0, 0]) + cy = self.CAB_Y + z = 1.30 + way = [(0.48, -0.014), (0.61, -0.008), (0.59, 0.08), (0.53, 0.16), (0.45, 0.23), (0.38, 0.28)] + way = [np.array([x, cy + s * dy, z]) for x, dy in way] + yield from self.reach(side, way[0], fx, self.qcmd[side], n=40, settle=0) + self.mark('sweep_e1_' + side) + yield from self.reach(side, way[1], fx, self.qcmd[side], n=30, settle=0) + self.mark('sweep_e2_' + side) + for a, b in zip(way[1:-1], way[2:]): + n = 50 + for i in range(n): + p = a + (b - a) * (i + 1) / n + if i % 3 == 0: + qs, _ = self.solve(side, p, fx, self.qcmd[side]) + self.qcmd[side] = qs + yield + self.mark('sweep_' + side) + self.base_on = True + return + if DEBUG.get('spring_test'): + self.grip[side] = 0.0 + yield from self.wait(20) + p = K.tool_world(self.q, side, 0.18)[:3, 3] - np.array([0.06, 0, 0]) + qs, _ = self.solve(side, p, xd, self.qcmd[side]) + yield from self.joints(30, **{side: qs}) + for k in range(4): + yield from self.wait(30) + self.mark('spring%d' % k) + self.base_on = True + return + # continue along the door arc + H = g[:2] + np.array([0.03, s * 0.28]) + r0 = g[:2] - H + th_a = np.arcsin(self.PULL0 / np.linalg.norm(r0)) + th_b = np.radians(self.DOOR_ARC) + n = 220 + bx0 = self.q[21] + self.base.target[0] = self.q[21] + self.base.target[1] = self.q[22] + self.base_on = True + for i in range(n + 1): + f = smooth(i / n) + th = th_a + (th_b - th_a) * f + self.base.target[0] = bx0 - self.PULL_WALK * f + Rz = K.rz(-s * th)[:2, :2] + p = H + Rz @ r0 + tli = tl + (0.3 - tl) * f + dxy = Rz @ np.array([np.cos(tli), 0.0]) + if i % 3 == 0: + qs, _ = self.solve(side, (p[0], p[1], hz), (dxy[0], dxy[1], np.sin(tli)), self.qcmd[side]) + self.qcmd[side] = qs + if DEBUG.get('servo_marks') and i % 50 == 0: + self.mark('arc%d' % i) + yield + self.grip[side] = 0.0 + yield from self.wait(15) + self.mark('door_released_' + side) + if DEBUG.get('stop_after_pull') or True: + t = K.tool_world(self.q, side, 0.18) + p = t[:3, 3] - 0.07 * t[:3, 0] + qs, _ = self.solve(side, p, t[:3, 0], self.qcmd[side]) + yield from self.joints(20, **{side: qs}) + p[2] = 1.10 + qs, _ = self.solve(side, p, t[:3, 0], self.qcmd[side]) + yield from self.joints(20, **{side: qs}) + self.mark('door_retracted_' + side) + self.base_on = True + return + H = g[:2] + np.array([0.05, s * 0.28]) + r0 = g[:2] - H + th_max = np.radians(40) + n = 200 + for i in range(n + 1): + th = th_max * smooth(i / n) + Rz = K.rz(-s * th)[:2, :2] + p = H + Rz @ r0 + dxy = Rz @ np.array([np.cos(tl), 0.0]) + if i % 3 == 0: + qs, _ = self.solve(side, (p[0], p[1], hz), (dxy[0], dxy[1], np.sin(tl)), self.qcmd[side]) + self.qcmd[side] = qs + if DEBUG.get('servo_marks') and i % 40 == 0: + self.mark('pull%d' % i) + yield + self.mark('door_pulled_' + side) + self.grip[side] = 0.0 + yield from self.wait(30) + self.mark('door_released_' + side) + # back off, close the fingers and push the door open from the inside + t = K.tool_world(self.q, side, 0.18) + p = t[:3, 3] - 0.06 * t[:3, 0] + qs, _ = self.solve(side, p, t[:3, 0], self.qcmd[side]) + yield from self.joints(30, **{side: qs}) + self.grip[side] = 1.0 + r, c = 0.22, 0.07 + + def P(th): + Rz = K.rz(-s * th)[:2, :2] + return H + Rz @ np.array([c, -s * r]) + + def D(th): + Rz = K.rz(-s * th * 0.5)[:2, :2] + return np.r_[Rz @ np.array([1.0, 0.0]), 0.0] + + th0 = th_max + E = H + K.rz(-s * th0)[:2, :2] @ np.array([0.0, -s * 0.33]) + G = np.r_[E + np.array([0.0, -s * 0.07]), hz] + yield from self.reach(side, G, D(0), self.qcmd[side], n=50, settle=0) + self.mark('push_gap_' + side) + p0 = P(th0 - 0.1) + yield from self.reach(side, np.r_[p0, hz], D(th0), self.qcmd[side], n=50, settle=0) + self.mark('push_in_' + side) + n = 200 + th1 = np.radians(100) + for i in range(n + 1): + th = th0 - 0.1 + (th1 - th0 + 0.1) * smooth(i / n) + if i % 3 == 0: + qs, _ = self.solve(side, np.r_[P(th), hz], D(th), self.qcmd[side]) + self.qcmd[side] = qs + if DEBUG.get('servo_marks') and i % 50 == 0: + self.mark('push%d' % i) + yield + self.mark('door_pushed_' + side) + self.base_on = True diff --git a/policies/put_cups/opus-s3/vision.py b/policies/put_cups/opus-s3/vision.py new file mode 100644 index 0000000000000000000000000000000000000000..efc0b6d45f1d07fb19043c615ba2c2d5a114c584 --- /dev/null +++ b/policies/put_cups/opus-s3/vision.py @@ -0,0 +1,139 @@ +"""Image processing for the policy (84x84 RGB from the robot cameras).""" +import numpy as np +from scipy import ndimage + +import g1kin as K + + +def dark_bars(im, vmax=150, min_px=12): + """Dark grey elongated blobs (cabinet door handles). Returns list of dicts with + pixel coordinates (xs, ys).""" + im = im.astype(int) + mx = im.max(-1) + m = (mx < vmax) & (mx - im.min(-1) < 30) + # the black diamond markers at the left / right image borders + m[:, :4] = False + m[:, 80:] = False + lab, n = ndimage.label(m) + out = [] + for k in range(1, n + 1): + ys, xs = np.nonzero(lab == k) + if len(ys) < min_px: + continue + h = ys.max() - ys.min() + 1 + w = xs.max() - xs.min() + 1 + if max(h, w) < 2.0 * min(h, w) or max(h, w) < 8: + continue + out.append(dict(xs=xs, ys=ys, n=len(ys), cu=xs.mean(), cv=ys.mean())) + return out + + +def handle_bars(im, M=None, xplane=0.62): + """Thick vertical dark bars: list of (cu, width, n) sorted by cu, measured on + the central row band. With a camera pose M, also the world y / z extent of + the bar on the plane x = xplane.""" + out = [] + for b in dark_bars(im, vmax=165, min_px=30): + rows = np.unique(b['ys']) + if len(rows) < 15: + continue + sel = np.abs(b['ys'] - 45) < 15 + if sel.sum() < 10: + continue + xs, ys = b['xs'][sel], b['ys'][sel] + rr = np.unique(ys) + wid = float(np.median([np.sum(ys == r) for r in rr])) + if wid < 3: + continue + d = dict(cu=float(xs.mean()) + 0.5, width=wid, n=b['n'], + top=int(b['ys'].min()), bot=int(b['ys'].max())) + if M is not None: + w = bar_world(b, M, xplane) + if w is None: + continue + d.update(y=w['y'], zmin=w['zmin'], zmax=w['zmax']) + out.append(d) + return sorted(out, key=lambda d: d['cu']) + + +HEAD = (83.52, 0.0805, 0.5255, 1.1673, -0.0343) # f, x, z, pitch, yaw (torso frame) +COUNTER_Z = 0.933 +CUP_R = 0.039 + + +def head_M(q): + f, hx, hz, hp, hyaw = HEAD + return K.base_M(q) @ K.torso_M(q[0:3]) @ K.T(K.rz(hyaw) @ K.ry(hp), (hx, 0, hz)) + + +def cup_mask(im): + im = im.astype(int) + mx = im.max(-1) + mn = im.min(-1) + return (mx - mn < 22) & (mx > 110) & (mx < 250) + + +def head_cups(im, q, min_px=25): + """Cup positions (x, y) on the counter from the head camera image.""" + m = cup_mask(im) + m[45:, :] = False # counter region is the upper part of the head image + lab, n = ndimage.label(m) + M = head_M(q) + f = HEAD[0] + out = [] + for k in range(1, n + 1): + ys, xs = np.nonzero(lab == k) + if len(ys) < min_px: + continue + if xs.max() - xs.min() < 5: + continue + bot = ys.max() + sel = ys >= bot - 2 + u = xs[sel].mean() + 0.5 + v = bot + 0.5 + d = np.array([1.0, -(u - 41.5) / f, -(v - 41.5) / f]) + d = M[:3, :3] @ d + o = M[:3, 3] + t = (COUNTER_Z - o[2]) / d[2] + p = o + t * d + hd = d[:2] / np.linalg.norm(d[:2]) + c = p[:2] + CUP_R * hd + out.append(dict(x=float(c[0]), y=float(c[1]), n=len(ys), u=float(u), v=float(v), + left=int(xs.min()), right=int(xs.max()), top=int(ys.min()))) + return out + + +def wrist_cup(im): + """The cup blob nearest the image centre column in a wrist image.""" + m = cup_mask(im) + m[:, :4] = False + m[:, 80:] = False + lab, n = ndimage.label(m) + best = None + for k in range(1, n + 1): + ys, xs = np.nonzero(lab == k) + if len(ys) < 80 or ys.mean() > 62: + continue + cu = xs.mean() + 0.5 + c = abs(cu - 41.5) + if best is None or c < best[0]: + best = (c, dict(cu=float(cu), cv=float(ys.mean()), n=len(ys), top=int(ys.min()), bot=int(ys.max()))) + return None if best is None else best[1] + + +def bar_world(bar, M, xplane): + """Intersect the rays of a bar's pixels with the plane x = xplane; + return mean y, min z, max z.""" + pts = [] + for u, v in zip(bar['xs'], bar['ys']): + o, d = K.pixel_ray(M, u + 0.5 - 0.5, v) + if abs(d[0]) < 1e-3: + continue + t = (xplane - o[0]) / d[0] + if t <= 0: + continue + pts.append(o + t * d) + pts = np.array(pts) + if len(pts) == 0: + return None + return dict(y=float(np.median(pts[:, 1])), zmin=float(pts[:, 2].min()), zmax=float(pts[:, 2].max())) diff --git a/policies/reach_target_dual/astra-s1/episodes.csv b/policies/reach_target_dual/astra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..bccfdeee9af3d7af1349005b9cd51468663b5fd8 --- /dev/null +++ b/policies/reach_target_dual/astra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,485,success,0 +620001,1,455,success,0 +620002,1,475,success,0 +620003,1,430,success,0 +620004,1,346,success,0 +620005,1,630,success,0 +620006,1,480,success,0 +620007,1,485,success,0 +620008,1,361,success,0 +620009,1,366,success,0 +620010,1,365,success,0 +620011,1,346,success,0 +620012,1,405,success,0 +620013,1,461,success,0 +620014,1,545,success,0 +620015,1,430,success,0 +620016,1,551,success,0 +620017,1,581,success,0 +620018,1,631,success,0 +620019,1,465,success,0 +620020,1,405,success,0 +620021,1,431,success,0 +620022,1,611,success,0 +620023,1,335,success,0 +620024,1,352,success,0 +620025,1,528,success,0 +620026,1,365,success,0 +620027,1,634,success,0 +620028,1,375,success,0 +620029,1,465,success,0 +620030,1,500,success,0 +620031,1,340,success,0 +620032,1,425,success,0 +620033,1,490,success,0 +620034,1,496,success,0 +620035,1,440,success,0 +620036,1,450,success,0 +620037,1,336,success,0 +620038,1,480,success,0 +620039,1,391,success,0 +620040,1,346,success,0 +620041,1,391,success,0 +620042,1,340,success,0 +620043,1,371,success,0 +620044,1,400,success,0 +620045,1,416,success,0 +620046,1,340,success,0 +620047,1,445,success,0 +620048,1,335,success,0 +620049,1,395,success,0 +620050,1,415,success,0 +620051,1,522,success,0 +620052,1,425,success,0 +620053,1,486,success,0 +620054,1,501,success,0 +620055,1,536,success,0 +620056,1,355,success,0 +620057,1,456,success,0 +620058,1,441,success,0 +620059,1,495,success,0 +620060,1,481,success,0 +620061,1,495,success,0 +620062,1,435,success,0 +620063,1,385,success,0 +620064,1,506,success,0 +620065,1,525,success,0 +620066,1,395,success,0 +620067,1,510,success,0 +620068,1,391,success,0 +620069,1,501,success,0 +620070,1,535,success,0 +620071,1,445,success,0 +620072,1,480,success,0 +620073,1,361,success,0 +620074,1,414,success,0 +620075,1,400,success,0 +620076,1,395,success,0 +620077,1,470,success,0 +620078,1,480,success,0 +620079,1,495,success,0 +620080,1,425,success,0 +620081,1,335,success,0 +620082,1,376,success,0 +620083,1,346,success,0 +620084,1,504,success,0 +620085,1,304,success,0 +620086,1,491,success,0 +620087,1,410,success,0 +620088,1,520,success,0 +620089,1,358,success,0 +620090,1,350,success,0 +620091,1,520,success,0 +620092,1,425,success,0 +620093,1,596,success,0 +620094,1,341,success,0 +620095,1,375,success,0 +620096,1,335,success,0 +620097,1,421,success,0 +620098,1,395,success,0 +620099,1,395,success,0 diff --git a/policies/reach_target_dual/astra-s1/policy.py b/policies/reach_target_dual/astra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..f20661e9910deaae5825fffbaabc4c80cf1cb2dc --- /dev/null +++ b/policies/reach_target_dual/astra-s1/policy.py @@ -0,0 +1,168 @@ +"""Deterministic, hand-written binocular reaching with wrist visual feedback. + +The head view initializes the reach. Each wrist independently centers its +assigned color and regulates apparent sphere size. All gains and thresholds +are fixed control constants; there are no trained models or seed-specific data. +""" + +import cv2 +import numpy as np + + +def detect(image, color): + """Return centroid, visible area and extent of the largest colored blob.""" + red, green, blue = image.astype(float).transpose(2, 0, 1) + if color == 0: + mask = (red > green * 1.6) & (red > blue * 1.6) & (red > 40) + else: + mask = (green > red * 1.5) & (green > blue * 1.3) & (green > 35) + count, labels, stats, centers = cv2.connectedComponentsWithStats( + mask.astype("uint8") + ) + if count < 2: + return None + index = 1 + np.argmax(stats[1:, 4]) + x, y, width, height, area = stats[index] + if area < 4: + return None + return np.array([*centers[index], area, width, height]) + + +class Policy: + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action()).copy() + self.a[18:] = 0 # Open fingers for the touch. + image = tools.image("head") + self.start = obs["low_dim_obs"][18:22].copy() + for side in range(2): + target = detect(image, side) + joint = 4 + 7 * side + self.a[joint] = ( + -0.25 if target is None + else np.clip((target[1] - 40) * 0.007, -0.5, 0) + ) + self.a[joint + 1] = 0.12 if side == 0 else -0.12 + self.ds = [None, None] + self.close = False + self.close_t = 0 + self.areas = [0., 0.] + self.finish = [0, 0] + self.reposition = 0 + self.repositioned = 0 + self.maxareas = [0., 0.] + + def act(self, obs, tools): + t = obs["t"] + + # A widely separated pair of depths can exhaust one arm's reach. + # Retract both arms and take one small step before resuming feedback. + if ( + self.close and self.repositioned < 2 and t - self.close_t > (80 if self.repositioned else 100) + and any( + not self.finish[s] and self.a[7 + 7 * s] > 0.8 + and self.areas[s] < 5200 + for s in range(2) + ) + ): + self.repositioned += 1 + self.reposition = t + 50 + self.finish = [0, 0] + for joint in (4, 11): + self.a[joint + 3] -= 0.3 + self.a[joint] += 0.24 + self.close_t = t + 50 + if t < self.reposition: + self.a[0] = 0.06 + return self.a + + # Allow the initial arm motion to settle; then update vision at 10 Hz. + if t >= 40 and t % 5 == 0: + for side, camera in enumerate(("left_wrist", "right_wrist")): + target = detect(tools.image(camera), side) + self.ds[side] = target + joint = 4 + 7 * side + + # Near the sphere surface, clipping can remove the color from + # the image. Avoid treating this as a distant target. + if ( + self.close and self.repositioned and self.maxareas[side] > 6000 + and (target is None or target[2] < 3500) + and not self.finish[side] + ): + self.finish[side] = 11 + if target is not None: + self.maxareas[side] = max(self.maxareas[side], target[2]) + + if self.finish[side]: + # Finish with a short coordinated shoulder/elbow reach. + if self.finish[side] <= 10: + self.a[joint + 3] += 0.025 + self.a[joint] -= 0.020 + self.finish[side] += 1 + # Correct residual drift after the final motion settles. + if ( + self.finish[side] > 20 and target is not None + and 1500 < target[2] < 6500 + ): + if abs(target[1] - 40) > 3: + self.a[joint] += np.clip( + (target[1] - 40) * 0.0006, -0.015, 0.015 + ) + if abs(target[0] - 41.5) > 3: + self.a[joint + 1] += np.clip( + (41.5 - target[0]) * 0.0006, -0.015, 0.015 + ) + if ( + self.finish[side] > 20 and target is not None + and 4000 < target[2] < 6800 + and abs(target[0] - 41.5) < 8 + and abs(target[1] - 40) < 8 + ): + advance = np.clip(0.04 * (np.sqrt(6800 / target[2]) - 1), 0, 0.008) + self.a[joint + 3] += advance + self.a[joint] -= 0.8 * advance + continue + + if target is not None: + self.areas[side] = target[2] + self.a[joint] += np.clip( + (target[1] - 40) * 0.001, -0.035, 0.035 + ) + # Roll handles outward motion. Use yaw for the remaining + # inward correction so the upper arm clears the torso. + delta = np.clip((41.5 - target[0]) * 0.001, -0.035, 0.035) + old_roll = self.a[joint + 1] + self.a[joint + 1] = np.clip( + old_roll + delta, + -0.08 if side == 0 else -0.9, + 0.9 if side == 0 else 0.08, + ) + self.a[joint + 2] += delta - (self.a[joint + 1] - old_roll) + + if self.close: + if ( + t - self.close_t > 100 and target[2] > 5800 + and abs(target[0] - 41.5) < 5 + and abs(target[1] - 40) < 5 + ): + self.finish[side] = 1 + # Apparent radius scales inversely with distance. + delta_elbow = np.clip( + 0.08 * (np.sqrt(6000 / target[2]) - 1), -0.015, 0.025 + ) + if target[2] > 6500: + delta_elbow = 0 + new_elbow = np.clip( + self.a[joint + 3] + delta_elbow, -0.7, 1.7 + ) + self.a[joint] -= 0.8 * (new_elbow - self.a[joint + 3]) + self.a[joint + 3] = new_elbow + + if max(self.areas) > 3300 and not self.close: + self.close = True + self.close_t = t + self.a[0] = 0.06 if t > 80 and not self.close else 0 + self.a[3] = np.clip( + -2 * (obs["low_dim_obs"][21] - self.start[3]), -0.2, 0.2 + ) + return self.a diff --git a/policies/reach_target_dual/astra-s2/episodes.csv b/policies/reach_target_dual/astra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..361bbb912cf176ef0baf48c595b4fe248016b5e4 --- /dev/null +++ b/policies/reach_target_dual/astra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,378,success,0 +620001,1,307,success,0 +620002,1,354,success,0 +620003,1,291,success,0 +620004,1,290,success,0 +620005,1,434,success,0 +620006,1,410,success,0 +620007,1,338,success,0 +620008,1,283,success,0 +620009,1,306,success,0 +620010,1,314,success,0 +620011,1,330,success,0 +620012,1,298,success,0 +620013,1,362,success,0 +620014,1,386,success,0 +620015,1,291,success,0 +620016,1,426,success,0 +620017,1,314,success,0 +620018,1,407,success,0 +620019,1,346,success,0 +620020,1,307,success,0 +620021,1,378,success,0 +620022,1,434,success,0 +620023,1,292,success,0 +620024,1,387,success,0 +620025,0,700,timeout,0 +620026,1,298,success,0 +620027,1,395,success,0 +620028,1,387,success,0 +620029,1,299,success,0 +620030,1,494,success,0 +620031,0,700,timeout,0 +620032,1,322,success,0 +620033,1,426,success,0 +620034,1,354,success,0 +620035,1,387,success,0 +620036,1,306,success,0 +620037,1,314,success,0 +620038,1,458,success,0 +620039,1,378,success,0 +620040,1,388,success,0 +620041,1,298,success,0 +620042,1,275,success,0 +620043,1,347,success,0 +620044,1,418,success,0 +620045,1,338,success,0 +620046,1,259,success,0 +620047,1,581,success,0 +620048,1,275,success,0 +620049,1,323,success,0 +620050,1,389,success,0 +620051,1,330,success,0 +620052,1,298,success,0 +620053,0,700,timeout,0 +620054,1,330,success,0 +620055,0,700,timeout,0 +620056,1,290,success,0 +620057,1,258,success,0 +620058,1,354,success,0 +620059,1,314,success,0 +620060,1,300,success,0 +620061,1,330,success,0 +620062,1,292,success,0 +620063,1,338,success,0 +620064,1,347,success,0 +620065,0,700,timeout,0 +620066,1,298,success,0 +620067,1,384,success,0 +620068,1,314,success,0 +620069,1,434,success,0 +620070,1,412,success,0 +620071,1,339,success,0 +620072,1,314,success,0 +620073,1,346,success,0 +620074,1,379,success,0 +620075,1,386,success,0 +620076,1,370,success,0 +620077,1,330,success,0 +620078,1,363,success,0 +620079,1,338,success,0 +620080,1,421,success,0 +620081,1,330,success,0 +620082,1,346,success,0 +620083,1,298,success,0 +620084,0,700,timeout,0 +620085,1,307,success,0 +620086,1,378,success,0 +620087,1,403,success,0 +620088,1,323,success,0 +620089,1,315,success,0 +620090,1,299,success,0 +620091,1,316,success,0 +620092,1,299,success,0 +620093,0,700,timeout,0 +620094,1,291,success,0 +620095,1,298,success,0 +620096,1,298,success,0 +620097,1,322,success,0 +620098,1,339,success,0 +620099,1,319,success,0 diff --git a/policies/reach_target_dual/astra-s2/policy.py b/policies/reach_target_dual/astra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..01dc5ffeed755ca9f0afb3bf9c66bb742b94784c --- /dev/null +++ b/policies/reach_target_dual/astra-s2/policy.py @@ -0,0 +1,96 @@ +"""Deterministic, hand-written visual servo for simultaneous sphere touching. + +Only RGB camera images and proprioception are used. Circle measurements are +computed geometrically from the current image; no learned model or stored +scene data is used. The head view initializes the approach, and the wrist +views close the arm-control loops. Bright target colors indicate contact. +""" +import numpy as np +import cv2 + +def sphere(im, side): + """Measure a colored sphere silhouette, excluding clipped image edges.""" + f = im.astype(float) + c = f[:, :, side] + other = np.maximum(f[:, :, 2], f[:, :, 1 - side]) + m = ((c > 35) & (c > other * 1.65)).astype(np.uint8) + contours, _ = cv2.findContours(m, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) + if not contours: + return None + pts = max(contours, key=cv2.contourArea).reshape(-1, 2).astype(float) + pts = pts[(pts[:, 0] > 1) & (pts[:, 0] < 82) & (pts[:, 1] > 1) & (pts[:, 1] < 82)] + if len(pts) < 8: + return None + x, y = pts.T + a = np.column_stack((2 * x, 2 * y, np.ones(len(x)))) + cx, cy, z = np.linalg.lstsq(a, x * x + y * y, rcond=None)[0] + radius = np.sqrt(max(1, z + cx * cx + cy * cy)) + return np.array([cx, cy, radius]) + +class Policy: + """Approach, visually align both hands, and hold each detected contact.""" + + def reset(self, obs, tools): + self.a = np.array(tools.hold_action()) + self.a[18:20] = 0 + self.a[4] = self.a[11] = -0.15 + self.last = [None, None] + self.contact = [False, False] + self.lateral = [0.3, -0.3] + self.close = [False, False] + self.recovery = [None, None] + self.x0 = obs['low_dim_obs'][18] + head = tools.image('head') + self.approach = 0.065 + for side, off in enumerate([4, 11]): + b = sphere(head, side) + if b is not None: + self.approach = max(self.approach, 0.065 + 2.0 * (1 / max(4.5, b[2]) - 1 / 7)) + self.lateral[side] = np.clip(((14 if side == 0 else 70) - b[0]) * 0.012, -0.35, 0.35) + + def act(self, obs, tools): + t = obs['t'] + if t > 170 and t % 8 == 0: + head = tools.image('head') + for s, off in enumerate([4, 11]): + im = tools.image(['left_wrist', 'right_wrist'][s]) + b = sphere(im, s) + self.contact[s] = bool(((head[:, :, s] > 230) & (head[:, :, 1 - s] < 100)).sum() > 3 or ((im[:, :, s] > 230) & (im[:, :, 1 - s] < 100)).sum() > 8) + self.last[s] = b + if t >= 480 and self.recovery[s] is None and (b is None) and self.close[s] and (not self.contact[s]) and (self.a[off + 3] >= 1.55): + self.recovery[s] = (t, float(self.a[off] + 0.7 * (self.a[off + 3] - 0.6))) + if self.recovery[s] is not None: + if not self.contact[s]: + start, center = self.recovery[s] + self.a[off + 3] = 0.6 + self.a[off] = center + 0.18 * np.cos((t - start) * np.pi / 100) + continue + colored = (im[:, :, s].astype(float) > 1.65 * np.maximum(im[:, :, 1 - s], im[:, :, 2])) & (im[:, :, s] > 35) + if colored.sum() > 6600 or (colored.sum() > 4000 and (b is None or b[2] < 30)) or (self.close[s] and (b is None or b[2] < 20)): + b = np.array([42, 42, 100.0]) + if b is not None and b[2] > 55: + self.close[s] = True + if b is None and (not self.contact[s]) and (not self.close[s]): + if t > 270: + self.a[off] = np.clip(self.a[off] + (0.035 if t < 400 else -0.05), -0.8, 0.3) + self.lateral[s] += 0.025 if s == 0 else -0.025 + self.lateral[s] = np.clip(self.lateral[s], -0.8, 0.8) + if b is not None and (not self.contact[s]): + u, v, r = b + self.a[off] += np.clip((v - 42) * 0.0015, -0.08, 0.08) + self.lateral[s] += np.clip((42 - u) * 0.0015, -0.06, 0.06) + if abs(v - 42) < 15 and abs(u - 42) < 15: + delta = min(0.05, 1.6 - self.a[off + 3]) + self.a[off + 3] += delta + self.a[off] -= 0.7 * delta + self.a[off + 3] = min(self.a[off + 3], 1.8) + self.a[0] = 0.12 if t < 140 and obs['low_dim_obs'][18] < self.x0 + self.approach else 0 + for s, off in enumerate([4, 11]): + lateral = self.lateral[s] + if s == 0 and lateral >= 0 or (s == 1 and lateral <= 0): + self.a[off + 1] = lateral + self.a[off + 2] = 0 + else: + self.a[off + 1] = 0 + self.a[off + 2] = lateral * 0.7 + return self.a diff --git a/policies/reach_target_dual/astra-s3/episodes.csv b/policies/reach_target_dual/astra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..2493808cf96faea1fd9e5d4569dbfa1b7ef19c34 --- /dev/null +++ b/policies/reach_target_dual/astra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,248,success,0 +620001,1,247,success,0 +620002,1,313,success,0 +620003,1,331,success,0 +620004,1,174,success,0 +620005,0,700,timeout,0 +620006,1,245,success,0 +620007,1,200,success,0 +620008,1,193,success,0 +620009,1,228,success,0 +620010,1,174,success,0 +620011,1,177,success,0 +620012,1,242,success,0 +620013,0,700,timeout,0 +620014,1,248,success,0 +620015,1,408,success,0 +620016,0,700,timeout,0 +620017,0,700,timeout,0 +620018,0,700,timeout,0 +620019,1,246,success,0 +620020,1,299,success,0 +620021,1,335,success,0 +620022,0,700,timeout,0 +620023,0,700,timeout,0 +620024,1,248,success,0 +620025,0,700,timeout,0 +620026,1,157,success,0 +620027,0,700,timeout,0 +620028,1,370,success,0 +620029,1,398,success,0 +620030,0,700,timeout,0 +620031,1,199,success,0 +620032,1,207,success,0 +620033,1,260,success,0 +620034,1,232,success,0 +620035,1,197,success,0 +620036,1,244,success,0 +620037,0,700,timeout,0 +620038,1,258,success,0 +620039,0,700,timeout,0 +620040,1,171,success,0 +620041,1,204,success,0 +620042,1,171,success,0 +620043,1,230,success,0 +620044,1,256,success,0 +620045,0,700,timeout,0 +620046,1,237,success,0 +620047,1,196,success,0 +620048,1,144,success,0 +620049,1,290,success,0 +620050,1,223,success,0 +620051,0,700,timeout,0 +620052,1,201,success,0 +620053,1,589,success,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,1,171,success,0 +620057,0,700,timeout,0 +620058,1,233,success,0 +620059,0,700,timeout,0 +620060,1,283,success,0 +620061,1,249,success,0 +620062,1,187,success,0 +620063,1,222,success,0 +620064,1,631,success,0 +620065,1,623,success,0 +620066,1,160,success,0 +620067,0,700,timeout,0 +620068,1,222,success,0 +620069,1,239,success,0 +620070,1,592,success,0 +620071,1,188,success,0 +620072,0,700,timeout,0 +620073,1,172,success,0 +620074,1,210,success,0 +620075,0,700,timeout,0 +620076,1,264,success,0 +620077,1,241,success,0 +620078,1,252,success,0 +620079,1,368,success,0 +620080,1,264,success,0 +620081,1,217,success,0 +620082,1,181,success,0 +620083,1,169,success,0 +620084,0,700,timeout,0 +620085,1,172,success,0 +620086,0,700,timeout,0 +620087,1,205,success,0 +620088,0,700,timeout,0 +620089,1,173,success,0 +620090,1,194,success,0 +620091,0,700,timeout,0 +620092,1,252,success,0 +620093,1,602,success,0 +620094,1,216,success,0 +620095,1,242,success,0 +620096,1,206,success,0 +620097,1,272,success,0 +620098,1,226,success,0 +620099,1,244,success,0 diff --git a/policies/reach_target_dual/astra-s3/policy.py b/policies/reach_target_dual/astra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..fdf485ec33291e5638e2d0bbde72149c1e31e702 --- /dev/null +++ b/policies/reach_target_dual/astra-s3/policy.py @@ -0,0 +1,118 @@ +"""Deterministic visual feedback control for simultaneous two-hand reaching. + +Only the three robot cameras and the supported action interface are used. +Sphere boundaries, hand silhouettes, and contact colors drive the controller; +there are no trained parameters, demonstrations, or seed-specific records. +""" + +import numpy as np +import cv2 +from itertools import combinations + +def sphere(im, j, prior=None): + """Recover a sphere silhouette, including arcs clipped by hands or borders.""" + m = (im[:, :, j] > im[:, :, 1 - j] * 1.8 + 25) & (im[:, :, j] > im[:, :, 2] * 1.8 + 25) + y, x = np.where(m) + if len(x) < 4: + return (None, m) + (cx, cy), r = cv2.minEnclosingCircle(np.array([x, y], np.float32).T) + # Restrict geometric circle candidates to edges against the blue floor. + floor = (im[:, :, 2] > im[:, :, 0] * 1.15) & (im[:, :, 2] > im[:, :, 1] * 1.12) + edge = m & (cv2.dilate(floor.astype(np.uint8), np.ones((3, 3), np.uint8)) > 0) + edge[[0, -1], :] = False + edge[:, [0, -1]] = False + y, x = np.where(edge) + pts = np.array([x, y], float).T + if len(pts) >= 6: + pts = pts[np.linspace(0, len(pts) - 1, min(20, len(pts))).astype(int)] + # Fixed, deterministic triples define analytic circumcircles. + tri = pts[np.array(list(combinations(range(len(pts)), 3)))] + a = tri[:, 1] - tri[:, 0] + b = tri[:, 2] - tri[:, 0] + det = 2 * (a[:, 0] * b[:, 1] - a[:, 1] * b[:, 0]) + valid = abs(det) > 4 + a = a[valid] + b = b[valid] + tri = tri[valid] + det = det[valid] + aa = (a * a).sum(1) + bb = (b * b).sum(1) + c = tri[:, 0] + np.stack([(aa * b[:, 1] - bb * a[:, 1]) / det, (bb * a[:, 0] - aa * b[:, 0]) / det], 1) + rad = np.linalg.norm(c - tri[:, 0], axis=1) + valid = (rad > 4) & (rad < 17) & (c[:, 0] > -14) & (c[:, 0] < 98) & (c[:, 1] > -14) & (c[:, 1] < 98) + c = c[valid] + rad = rad[valid] + if len(c): + err = np.abs(np.linalg.norm(c[:, None, :] - pts[None, :, :], axis=2) - rad[:, None]) + score = np.minimum(err, 2).mean(1) + if prior is not None: + score += 0.04 * abs(rad - prior) + k = score.argmin() + cx, cy = c[k] + r = rad[k] + 0.4 + return (np.array([cx, cy, r]), m) + +class Policy: + + def reset(self, obs, tools): + """Initialize a symmetric reach and independent arm search directions.""" + self.a = np.asarray(tools.hold_action(), float) + self.a[4:11] = [-0.65, 0.05, 0, 0.6, 0, 0, 0] + self.a[11:18] = [-0.65, -0.05, 0, 0.6, 0, 0, 0] + self.centers = [None, None] + self.rad = [0, 0] + self.lit = [False, False] + self.search = 0 + self.edir = [1, 1] + + def act(self, obs, tools): + t = obs['t'] + a = self.a + if t % 5 == 0: + # Visual feedback runs at 10 Hz; joint commands are held between frames. + im = tools.image('head').astype(float) + for j in range(2): + result, color = sphere(im, j, self.rad[j] or None) + if result is not None: + self.centers[j] = result[:2] + self.rad[j] = result[2] + self.lit[j] = bool(color.any() and np.sum(im[:, :, j][color] > 240) > 3) + if result is None or (self.centers[j] is not None and (self.centers[j][0] < 2 or self.centers[j][0] > 81)): + wi = tools.image(['left_wrist', 'right_wrist'][j]).astype(float) + wm = (wi[:, :, j] > wi[:, :, 1 - j] * 1.8 + 25) & (wi[:, :, j] > wi[:, :, 2] * 1.8 + 25) + self.lit[j] = self.lit[j] or np.sum(wm & (wi[:, :, j] > 240)) > 3 + # Extrapolate the fingertip from the top of the white hand silhouette. + white = (im.min(2) > 150) & (im.max(2) - im.min(2) < 55) + white[:, 41:] = False if j == 0 else white[:, 41:] + if j == 1: + white[:, :42] = False + yy, xx = np.where(white & (np.indices((84, 84))[0] < 65)) + if len(xx) > 5 and self.centers[j] is not None: + y0 = np.percentile(yy, 4) + sel = (yy >= y0) & (yy < y0 + 9) + if not sel.any(): + continue + xt = np.mean(xx[sel]) + lo = (yy >= y0 + 9) & (yy < y0 + 19) + slope = (np.mean(xx[lo]) - xt) / 10 if lo.any() else 0 + hand = np.array([xt - np.clip(slope * 3, -4, 4), y0 - 3]) + err = self.centers[j] - hand + off = 4 + 7 * j + if t > 25 and (not self.lit[j]): + a[off] += np.clip(err[1] * 0.006, -0.045, 0.045) + a[off + 1] -= np.clip(err[0] * 0.008, -0.04, 0.04) + if t > 50: + if any(self.lit): + self.search += 1 + for j in range(2): + if not self.lit[j] and any(self.lit): + # Coordinate shoulder and elbow to vary depth at nearly fixed bearing. + a[7 + 7 * j] += 0.006 * self.edir[j] + a[4 + 7 * j] -= 0.0039 * self.edir[j] + if a[7 + 7 * j] > 1.65: + self.edir[j] = -1 + if a[7 + 7 * j] < 0.2: + self.edir[j] = 1 + # Stop on contact; short approach pulses help the remaining hand reach. + a[0] = 0.1 if t < 550 and (not any(self.lit) or (not all(self.lit) and self.search > 100 and (self.search % 100 < 40) and all((4 < c[0] < 79 for c in self.centers if c is not None)))) else 0 + return a.copy() diff --git a/policies/reach_target_dual/deepseek1017-s1/episodes.csv b/policies/reach_target_dual/deepseek1017-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..d4259e14792ad4d9aececc823bab7ba61bf11e96 --- /dev/null +++ b/policies/reach_target_dual/deepseek1017-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,700,timeout,0 +620001,0,700,timeout,0 +620002,0,700,timeout,0 +620003,0,700,timeout,0 +620004,0,700,timeout,0 +620005,0,700,timeout,0 +620006,0,700,timeout,0 +620007,0,700,timeout,0 +620008,0,700,timeout,0 +620009,0,700,timeout,0 +620010,0,700,timeout,0 +620011,0,700,timeout,0 +620012,0,700,timeout,0 +620013,0,700,timeout,0 +620014,0,700,timeout,0 +620015,0,700,timeout,0 +620016,0,700,timeout,0 +620017,0,700,timeout,0 +620018,0,700,timeout,0 +620019,0,700,timeout,0 +620020,0,700,timeout,0 +620021,0,700,timeout,0 +620022,0,700,timeout,0 +620023,0,700,timeout,0 +620024,0,700,timeout,0 +620025,0,700,timeout,0 +620026,0,700,timeout,0 +620027,0,700,timeout,0 +620028,0,700,timeout,0 +620029,0,700,timeout,0 +620030,0,700,timeout,0 +620031,0,700,timeout,0 +620032,0,700,timeout,0 +620033,0,700,timeout,0 +620034,0,700,timeout,0 +620035,0,700,timeout,0 +620036,0,700,timeout,0 +620037,0,700,timeout,0 +620038,0,700,timeout,0 +620039,0,700,timeout,0 +620040,0,700,timeout,0 +620041,0,700,timeout,0 +620042,0,700,timeout,0 +620043,0,700,timeout,0 +620044,0,700,timeout,0 +620045,0,700,timeout,0 +620046,0,700,timeout,0 +620047,0,700,timeout,0 +620048,0,700,timeout,0 +620049,0,700,timeout,0 +620050,0,700,timeout,0 +620051,0,700,timeout,0 +620052,0,700,timeout,0 +620053,0,700,timeout,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,0,700,timeout,0 +620058,0,700,timeout,0 +620059,0,700,timeout,0 +620060,0,700,timeout,0 +620061,0,700,timeout,0 +620062,0,700,timeout,0 +620063,0,700,timeout,0 +620064,0,700,timeout,0 +620065,0,700,timeout,0 +620066,0,700,timeout,0 +620067,0,700,timeout,0 +620068,0,700,timeout,0 +620069,0,700,timeout,0 +620070,0,700,timeout,0 +620071,0,700,timeout,0 +620072,0,700,timeout,0 +620073,0,700,timeout,0 +620074,0,700,timeout,0 +620075,0,700,timeout,0 +620076,0,700,timeout,0 +620077,0,700,timeout,0 +620078,0,700,timeout,0 +620079,0,700,timeout,0 +620080,0,700,timeout,0 +620081,0,700,timeout,0 +620082,0,700,timeout,0 +620083,0,700,timeout,0 +620084,0,700,timeout,0 +620085,0,700,timeout,0 +620086,0,700,timeout,0 +620087,0,700,timeout,0 +620088,0,700,timeout,0 +620089,0,700,timeout,0 +620090,0,700,timeout,0 +620091,0,700,timeout,0 +620092,0,700,timeout,0 +620093,0,700,timeout,0 +620094,0,700,timeout,0 +620095,0,700,timeout,0 +620096,0,700,timeout,0 +620097,0,700,timeout,0 +620098,0,700,timeout,0 +620099,0,700,timeout,0 diff --git a/policies/reach_target_dual/deepseek1017-s1/policy.py b/policies/reach_target_dual/deepseek1017-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..0143bf840d262dda47b06b8ed94f1c619a88d574 --- /dev/null +++ b/policies/reach_target_dual/deepseek1017-s1/policy.py @@ -0,0 +1,190 @@ +"""Hand-written control policy for the reach_target_dual task. + +Task: touch the red sphere with the left hand and the green sphere with the +right hand at the same time. + +Outline + 1. detect the red and green spheres in the head camera (colour blobs), + 2. turn in place until the pair is centred in front of the robot, + 3. optionally take a short step towards the spheres (only when their + apparent size says they are still far away; the walk is capped), + 4. raise both arms into the reach posture; the shoulder roll of each arm + follows the measured bearing of its sphere, the elbow follows the + apparent size, and a small wrist-camera image servo trims the approach, + 5. hold the reach posture for the rest of the episode. + +All numbers were tuned by running episodes on the development seeds. The +policy contains no learned component, uses no randomness and no wall clock. +""" + +import numpy as np + +# head camera model, calibrated offline from the robot's own motion +F = 64.4 +CX = 36.7 +CY = 30.0 + +HEIGHT = 0.745 + +# reach posture measured at the initial pose of the robot +L_BASE = np.array([-0.80, 0.40, 0.00, 0.88, 0.0, 0.0, 0.0], np.float32) +R_BASE = np.array([-0.92, -0.30, 0.00, 0.82, 0.0, 0.0, 0.0], np.float32) + + +def _blob(mask): + """Centroid/size descriptor of a boolean mask (largest blob).""" + ys, xs = np.nonzero(mask) + if len(xs) < 8: + return None + return (float(xs.mean()), float(ys.mean()), int(len(xs)), + int(xs.min()), int(xs.max()), int(ys.min()), int(ys.max())) + + +def _detect(im): + r = im[..., 0].astype(np.int32) + g = im[..., 1].astype(np.int32) + b = im[..., 2].astype(np.int32) + red = (r > 55) & (r > g * 1.30 + 8) & (r > b * 1.30 + 8) + green = (g > 32) & (g > r * 1.18 + 5) & (g > b * 1.05 + 2) + return {"R": _blob(red), "G": _blob(green)} + + +def _wrist_blob(im, colour): + if im is None: + return None + r = im[..., 0].astype(np.int32) + g = im[..., 1].astype(np.int32) + b = im[..., 2].astype(np.int32) + if colour == "R": + m = (r > 30) & (r > g * 1.35 + 6) & (r > b * 1.35 + 6) + else: + m = (g > 15) & (g > r * 1.22 + 4) & (g > b * 1.05 + 2) + return _blob(m) + + +def _diam(b): + if b is None: + return None + return 0.5 * ((b[4] - b[3]) + (b[6] - b[5])) + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.t = 0 + self.la = L_BASE.copy() + self.ra = R_BASE.copy() + self.la0 = None + self.ra0 = None + self.dia0 = None + self.walked = 0 + self.reach_t = 0 + self.fell = False + + # ------------------------------------------------------------------ # + def act(self, obs, tools): + self.t += 1 + if bool(obs.get("fell", False)): + self.fell = True + raw = self.hold.copy() + raw[0] = 0.0 + raw[1] = 0.0 + raw[3] = 0.0 + raw[2] = HEIGHT + + try: + det = _detect(tools.image("head", 84, 84)) + except Exception: + det = {"R": None, "G": None} + R, G = det["R"], det["G"] + dR, dG = _diam(R), _diam(G) + + # ---- settle and locate the spheres ------------------------------ + if self.t <= 10: + raw[4:11] = self.hold[4:11] + raw[11:18] = self.hold[11:18] + return raw + + if self.t <= 90: + if R is not None and G is not None: + err = 0.5 * (R[0] + G[0]) - 41.5 + elif R is not None: + err = R[0] - 26.0 + elif G is not None: + err = G[0] - 57.0 + else: + err = 25.0 * np.sin(0.03 * self.t) + wz = float(np.clip(-0.0045 * err, -0.4, 0.4)) + raw[3] = 0.0 if abs(wz) < 0.06 else wz + raw[4:11] = self.hold[4:11] + raw[11:18] = self.hold[11:18] + ds = [d for d in (dR, dG) if d is not None] + if ds: + self.dia0 = float(np.mean(ds)) + return raw + + # ---- approach --------------------------------------------------- + # the reach posture was measured when the spheres subtend about + # 11.5 px in the head image; walk only when they look farther away. + if self.t <= 170 and not self.fell and self.walked < 45: + ds = [d for d in (dR, dG) if d is not None] + cur = float(np.mean(ds)) if ds else None + ref = self.dia0 if self.dia0 else 11.5 + if cur is not None and cur < 0.92 * max(ref, 11.5): + if R is not None and G is not None: + err = 0.5 * (R[0] + G[0]) - 41.5 + wz = float(np.clip(-0.004 * err, -0.25, 0.25)) + raw[3] = 0.0 if abs(wz) < 0.06 else wz + raw[0] = 0.14 + self.walked += 1 + raw[4:11] = self.hold[4:11] + raw[11:18] = self.hold[11:18] + return raw + + # ---- reach ------------------------------------------------------ + if self.la0 is None: + self.reach_t = self.t + self.la0 = np.asarray(obs["low_dim_obs"][0:7], np.float32) + self.ra0 = np.asarray(obs["low_dim_obs"][9:16], np.float32) + la = L_BASE.copy() + ra = R_BASE.copy() + if R is not None: + az = np.arctan2(R[0] - CX, F) + dia = dR if dR else 12.0 + la[1] = float(np.clip(-1.0 * az + 0.02, -0.15, 1.05)) + la[3] = float(np.clip(0.88 * (dia / 12.0), 0.45, 1.30)) + if G is not None: + az = np.arctan2(G[0] - CX, F) + dia = dG if dG else 12.0 + ra[1] = float(np.clip(-0.60 * az - 0.02, -1.05, 0.15)) + ra[3] = float(np.clip(0.82 * (dia / 12.0), 0.45, 1.30)) + self.la = la + self.ra = ra + + k = min(1.0, (self.t - self.reach_t) / 42.0) + k = k * k * (3.0 - 2.0 * k) + la = self.la0 + (self.la - self.la0) * k + ra = self.ra0 + (self.ra - self.ra0) * k + + # gentle wrist-image servo once the posture is reached + if k >= 1.0 and not self.fell: + try: + lm = _wrist_blob(tools.image("left_wrist", 84, 84), "R") + except Exception: + lm = None + if lm is not None and lm[2] > 40: + la[1] = float(np.clip(la[1] + 0.0025 * (42.0 - lm[0]) + - 0.0010 * (lm[1] - 42.0), -0.2, 1.1)) + self.la[1] = la[1] + try: + rm = _wrist_blob(tools.image("right_wrist", 84, 84), "G") + except Exception: + rm = None + if rm is not None and rm[2] > 40: + ra[1] = float(np.clip(ra[1] + 0.0025 * (42.0 - rm[0]) + - 0.0010 * (rm[1] - 42.0), -1.1, 0.2)) + self.ra[1] = ra[1] + + raw[4:11] = la + raw[11:18] = ra + return raw diff --git a/policies/reach_target_dual/deepseek1017-s2/episodes.csv b/policies/reach_target_dual/deepseek1017-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..861af4d4895d345c8532b41d64507180bc3d6560 --- /dev/null +++ b/policies/reach_target_dual/deepseek1017-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,700,timeout,0 +620001,0,700,timeout,0 +620002,0,700,timeout,0 +620003,0,700,timeout,0 +620004,0,700,timeout,0 +620005,0,700,timeout,0 +620006,0,700,timeout,0 +620007,0,700,timeout,0 +620008,1,119,success,0 +620009,1,613,success,0 +620010,1,581,success,0 +620011,0,700,timeout,0 +620012,0,700,timeout,0 +620013,0,700,timeout,0 +620014,0,700,timeout,0 +620015,0,700,timeout,0 +620016,0,700,timeout,0 +620017,0,700,timeout,0 +620018,0,700,timeout,0 +620019,0,700,timeout,0 +620020,0,700,timeout,0 +620021,0,700,timeout,0 +620022,0,700,timeout,0 +620023,0,700,timeout,0 +620024,0,700,timeout,0 +620025,0,700,timeout,0 +620026,0,700,timeout,0 +620027,0,700,timeout,0 +620028,0,700,timeout,0 +620029,0,700,timeout,0 +620030,0,700,timeout,0 +620031,0,700,timeout,0 +620032,0,700,timeout,0 +620033,0,700,timeout,0 +620034,1,657,success,0 +620035,1,593,success,0 +620036,0,700,timeout,0 +620037,0,700,timeout,0 +620038,0,700,timeout,0 +620039,0,700,timeout,0 +620040,1,150,success,0 +620041,0,700,timeout,0 +620042,0,700,timeout,0 +620043,0,700,timeout,0 +620044,0,700,timeout,0 +620045,0,700,timeout,0 +620046,1,609,success,0 +620047,1,159,success,0 +620048,1,106,success,0 +620049,0,700,timeout,0 +620050,0,700,timeout,0 +620051,0,700,timeout,0 +620052,0,700,timeout,0 +620053,1,112,success,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,1,572,success,0 +620057,1,120,success,0 +620058,0,700,timeout,0 +620059,0,700,timeout,0 +620060,1,179,success,0 +620061,0,700,timeout,0 +620062,0,700,timeout,0 +620063,1,585,success,0 +620064,0,700,timeout,0 +620065,0,700,timeout,0 +620066,1,120,success,0 +620067,0,700,timeout,0 +620068,0,700,timeout,0 +620069,0,700,timeout,0 +620070,0,700,timeout,0 +620071,0,700,timeout,0 +620072,0,700,timeout,0 +620073,0,700,timeout,0 +620074,0,700,timeout,0 +620075,0,700,timeout,0 +620076,0,700,timeout,0 +620077,0,700,timeout,0 +620078,0,700,timeout,0 +620079,1,625,success,0 +620080,0,700,timeout,0 +620081,1,175,success,0 +620082,1,587,success,0 +620083,0,700,timeout,0 +620084,0,700,timeout,0 +620085,0,700,timeout,0 +620086,0,700,timeout,0 +620087,0,700,timeout,0 +620088,0,700,timeout,0 +620089,0,700,timeout,0 +620090,1,612,success,0 +620091,0,700,timeout,0 +620092,0,700,timeout,0 +620093,0,700,timeout,0 +620094,0,700,timeout,0 +620095,0,700,timeout,0 +620096,1,113,success,0 +620097,0,700,timeout,0 +620098,0,700,timeout,0 +620099,0,700,timeout,0 diff --git a/policies/reach_target_dual/deepseek1017-s2/policy.py b/policies/reach_target_dual/deepseek1017-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d6f100f4ef2323c78527ec3cba9c3a1c5df45d46 --- /dev/null +++ b/policies/reach_target_dual/deepseek1017-s2/policy.py @@ -0,0 +1,268 @@ +"""Hand-written control policy for the Unitree G1 "touch two spheres" task. + +Task: touch the red sphere with the left hand and the green sphere with the +right hand at the same time. Only the robot's own cameras (head, left wrist, +right wrist) and its body state are available. + +Approach (hand-written control, no learned components): + +1. Move both arms into a reach posture whose wrist cameras look towards the + spheres. A small proportional controller on the wrist pitch/yaw joints (the + "aim servo") keeps each sphere centred in its wrist camera. +2. Command the base forward so the body approaches the spheres (they sit in + front of the robot at roughly chest height). +3. Squat a little: the hands then come down/forward onto the spheres. +4. Run a deterministic coordinate pattern search over the arm joints that + maximises how large the spheres appear in the wrist cameras, i.e. minimises + the distance between hands and spheres. When both spheres nearly fill the + wrist images the hands are on the spheres. +5. Hold that configuration; the task requires the contact to persist for 1 s. + +Every constant below was tuned by running episodes on the development seeds. +""" + +import numpy as np +import cv2 + +# --------------------------------------------------------------------------- +# tuned constants +# --------------------------------------------------------------------------- + +# reach posture that points both wrist cameras at the spheres +Q_L = np.array([-0.40, 0.20, 0.00, 0.30, 0.00, -0.25, -0.25], dtype=np.float64) +Q_R = np.array([-0.40, -0.20, 0.00, 0.30, 0.00, -0.12, 0.15], dtype=np.float64) + +HEIGHT_WALK = 0.74 # pelvis height while stepping +HEIGHT_REACH = 0.72 # pelvis height for the final reach (slight squat) +WALK_VX = 0.30 # forward velocity command while approaching +WALK_STEPS = 24 # control steps spent walking forward + +SETTLE_STEPS = 30 # let the arms settle into the reach posture +COAST_STEPS = 10 # let the base stop before squatting +SQUAT_STEPS = 16 # time given to the height command + +# wrist-aim servo +AIM_GAIN = 0.0010 # rad of wrist angle per pixel of centring error +AIM_DEADBAND = 3.0 # px +AIM_MAX_STEP = 0.05 # rad per control step +AIM_LIMIT = 1.40 # wrist pitch/yaw soft limit + +# pattern search +PROBE_STEPS = 14 # control steps per probe +PROBE_DELTAS = (0.13, -0.13) +PROBE_CAP = 46.0 # per-hand radius considered "touching" +ACCEPT_MARGIN = 3.0 +SEARCH_ITERS = 2 + +HOLD1_STEPS = 120 # hold the reach pose for a while (success may end it) +SWEEP_STEPS = 120 # half period of the final slow height sweep +SWEEP_LO = 0.63 # lowest pelvis height of the sweep +SWEEP_HI = 0.73 # highest pelvis height of the sweep + +RED = "red" +GREEN = "green" + + +# --------------------------------------------------------------------------- +# perception +# --------------------------------------------------------------------------- + + +def find_blob(im, kind): + """Largest blob of one colour in an RGB image. + + Returns ``(area, cu, cv, x, y, w, h)`` or ``None``. The thresholds are + deliberately permissive: the rendered spheres are quite dark on their + shaded side, so a strict brightness cut would under-segment them. + """ + a = im.astype(np.int16) + r, g, b = a[..., 0], a[..., 1], a[..., 2] + if kind == RED: + mask = (r > 28) & (r > 1.7 * g + 8) & (r > 1.7 * b + 8) + else: + mask = (g > 25) & (g > 1.45 * r + 6) & (g > 1.25 * b + 4) + m = mask.astype(np.uint8) + m = cv2.dilate(m, np.ones((3, 3), np.uint8), iterations=1) + n, lab, stats, cent = cv2.connectedComponentsWithStats(m, 8) + best = None + for i in range(1, n): + area = int(stats[i, cv2.CC_STAT_AREA]) + if area < 8: + continue + if best is None or area > best[0]: + best = (area, float(cent[i, 0]), float(cent[i, 1]), + int(stats[i, cv2.CC_STAT_LEFT]), int(stats[i, cv2.CC_STAT_TOP]), + int(stats[i, cv2.CC_STAT_WIDTH]), int(stats[i, cv2.CC_STAT_HEIGHT])) + return best + + +def blob_radius(b): + if b is None: + return 0.0 + return float(np.sqrt(b[0] / np.pi)) + + +# --------------------------------------------------------------------------- +# wrist aim servo +# --------------------------------------------------------------------------- + + +class AimServo: + """Keep a coloured sphere centred in one wrist camera via wrist pitch/yaw.""" + + def __init__(self, q, kind): + self.q = np.array(q, dtype=np.float64) + self.kind = kind + self.lost = 0 + self.search_t = 0 + + def update(self, b): + if b is not None: + self.lost = 0 + eu = b[1] - 42.0 + ev = b[2] - 42.0 + if abs(eu) > AIM_DEADBAND: + d = -AIM_GAIN * eu + d = max(-AIM_MAX_STEP, min(AIM_MAX_STEP, d)) + self.q[6] = float(np.clip(self.q[6] + d, -AIM_LIMIT, AIM_LIMIT)) + if abs(ev) > AIM_DEADBAND: + d = AIM_GAIN * ev + d = max(-AIM_MAX_STEP, min(AIM_MAX_STEP, d)) + self.q[5] = float(np.clip(self.q[5] + d, -AIM_LIMIT, AIM_LIMIT)) + else: + self.lost += 1 + if self.lost > 4: + # deterministic search: slow sweep of pitch, gentle yaw drift + self.search_t += 1 + self.q[5] = float(np.clip( + self.q[5] + 0.006 * np.sin(self.search_t * 0.25), + -AIM_LIMIT, AIM_LIMIT)) + self.q[6] = float(np.clip( + self.q[6] + 0.002 * np.cos(self.search_t * 0.10), + -AIM_LIMIT, AIM_LIMIT)) + + +# --------------------------------------------------------------------------- +# policy +# --------------------------------------------------------------------------- + + +class Policy: + """Reach both spheres, keep the contacts, hold them for a second.""" + + def __init__(self): + self._reset_state() + + def _reset_state(self): + self.phase = 0 + self.t = 0 + self.t_phase = 0 + self.servo_l = AimServo(Q_L, RED) + self.servo_r = AimServo(Q_R, GREEN) + self.hold = None + self.probes = self._build_probes() + self.probe_i = 0 + self.probe_saved = None + self.probe_score0 = 0.0 + self.p_t = 0 + self.score_sum = 0.0 + self.score_n = 0 + self.score_prev = 0.0 + + @staticmethod + def _build_probes(): + probes = [] + for _ in range(SEARCH_ITERS): + for arm in ("L", "R"): + for j in (0, 3, 1): # shoulder pitch, elbow, shoulder roll + for d in PROBE_DELTAS: + probes.append((arm, j, d)) + return probes + + def reset(self, obs, tools): + self._reset_state() + self.hold = np.asarray(tools.hold_action(), dtype=np.float64).copy() + + # -- helpers ----------------------------------------------------------- + def _score(self, lb, rb): + sl = min(blob_radius(lb), PROBE_CAP) + sr = min(blob_radius(rb), PROBE_CAP) + return min(sl, sr) + 0.25 * (sl + sr) + + def act(self, obs, tools): + raw = self.hold.copy() + height = HEIGHT_WALK + vx = 0.0 + + lb = find_blob(tools.image("left_wrist"), RED) + rb = find_blob(tools.image("right_wrist"), GREEN) + + ph = self.phase + if ph == 0: # settle into reach pose + if self.t_phase >= SETTLE_STEPS: + self._next_phase() + elif ph == 1: # step towards the spheres + vx = WALK_VX + if self.t_phase >= WALK_STEPS: + self._next_phase() + elif ph == 2: # let the base stop + if self.t_phase >= COAST_STEPS: + self._next_phase() + elif ph == 3: # squat + height = HEIGHT_REACH + if self.t_phase >= SQUAT_STEPS: + self._next_phase() + elif ph == 4: # hold the reach pose + height = HEIGHT_REACH + if self.t_phase >= HOLD1_STEPS: + self._next_phase() + elif ph == 5: # pattern search + height = HEIGHT_REACH + self._search_step(lb, rb) + elif ph == 6: # slow height sweep + tt = self.t_phase % (2 * SWEEP_STEPS) + if tt < SWEEP_STEPS: + height = SWEEP_HI - (SWEEP_HI - SWEEP_LO) * (tt / float(SWEEP_STEPS)) + else: + height = SWEEP_LO + (SWEEP_HI - SWEEP_LO) * ( + (tt - SWEEP_STEPS) / float(SWEEP_STEPS)) + else: # final hold + height = HEIGHT_REACH + + self.servo_l.update(lb) + self.servo_r.update(rb) + + raw[0] = vx + raw[2] = height + raw[4:11] = self.servo_l.q + raw[11:18] = self.servo_r.q + self.t += 1 + self.t_phase += 1 + return raw + + def _next_phase(self): + self.phase += 1 + self.t_phase = 0 + + def _search_step(self, lb, rb): + if self.probe_i >= len(self.probes): + self._next_phase() + return + arm, j, d = self.probes[self.probe_i] + servo = self.servo_l if arm == "L" else self.servo_r + if self.p_t == 0: + self.probe_saved = servo.q.copy() + self.probe_score0 = self._score(lb, rb) + self.score_sum = 0.0 + self.score_n = 0 + servo.q[j] += d + if self.p_t >= PROBE_STEPS - 5: + self.score_sum += self._score(lb, rb) + self.score_n += 1 + if self.p_t >= PROBE_STEPS - 1: + score = self.score_sum / max(self.score_n, 1) + if not score > self.probe_score0 + ACCEPT_MARGIN: + servo.q = self.probe_saved.copy() + self.probe_i += 1 + self.p_t = -1 + self.p_t += 1 diff --git a/policies/reach_target_dual/deepseek1017-s3/episodes.csv b/policies/reach_target_dual/deepseek1017-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..7ef469775ef2a558e292279d6347285cdda91396 --- /dev/null +++ b/policies/reach_target_dual/deepseek1017-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,700,timeout,0 +620001,1,189,success,0 +620002,0,700,timeout,0 +620003,1,163,success,0 +620004,1,338,success,0 +620005,0,700,timeout,0 +620006,0,700,timeout,0 +620007,1,208,success,0 +620008,1,268,success,0 +620009,1,161,success,0 +620010,1,148,success,0 +620011,1,242,success,0 +620012,0,700,timeout,0 +620013,0,700,timeout,0 +620014,0,700,timeout,0 +620015,0,700,timeout,0 +620016,1,400,success,0 +620017,1,374,success,0 +620018,0,700,timeout,0 +620019,1,298,success,0 +620020,1,377,success,0 +620021,0,700,timeout,0 +620022,0,700,timeout,0 +620023,1,310,success,0 +620024,1,226,success,0 +620025,0,700,timeout,0 +620026,1,221,success,0 +620027,0,700,timeout,0 +620028,0,700,timeout,0 +620029,1,166,success,0 +620030,0,700,timeout,0 +620031,1,146,success,0 +620032,1,238,success,0 +620033,0,700,timeout,0 +620034,0,700,timeout,0 +620035,0,700,timeout,0 +620036,1,161,success,0 +620037,0,700,timeout,0 +620038,0,700,timeout,0 +620039,0,700,timeout,0 +620040,0,700,timeout,0 +620041,1,466,success,0 +620042,0,700,timeout,0 +620043,1,262,success,0 +620044,0,700,timeout,0 +620045,0,700,timeout,0 +620046,0,700,timeout,0 +620047,1,175,success,0 +620048,1,131,success,0 +620049,1,226,success,0 +620050,0,700,timeout,0 +620051,0,700,timeout,0 +620052,0,700,timeout,0 +620053,0,700,timeout,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,0,700,timeout,0 +620058,0,700,timeout,0 +620059,0,700,timeout,0 +620060,0,700,timeout,0 +620061,1,359,success,0 +620062,0,700,timeout,0 +620063,0,700,timeout,0 +620064,0,700,timeout,0 +620065,0,700,timeout,0 +620066,0,700,timeout,0 +620067,0,700,timeout,0 +620068,0,700,timeout,0 +620069,0,700,timeout,0 +620070,0,700,timeout,0 +620071,0,700,timeout,0 +620072,0,700,timeout,0 +620073,0,700,timeout,0 +620074,1,191,success,0 +620075,0,700,timeout,0 +620076,0,700,timeout,0 +620077,0,700,timeout,0 +620078,1,235,success,0 +620079,0,700,timeout,0 +620080,1,218,success,0 +620081,0,700,timeout,0 +620082,1,181,success,0 +620083,1,242,success,0 +620084,0,700,timeout,0 +620085,0,700,timeout,0 +620086,0,700,timeout,0 +620087,1,290,success,0 +620088,0,700,timeout,0 +620089,1,134,success,0 +620090,0,700,timeout,0 +620091,0,700,timeout,0 +620092,0,700,timeout,0 +620093,0,700,timeout,0 +620094,0,700,timeout,0 +620095,0,700,timeout,0 +620096,0,700,timeout,0 +620097,1,313,success,0 +620098,1,184,success,0 +620099,1,145,success,0 diff --git a/policies/reach_target_dual/deepseek1017-s3/policy.py b/policies/reach_target_dual/deepseek1017-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..0272450f169670a9a8d4e96c7b8a8210f853958a --- /dev/null +++ b/policies/reach_target_dual/deepseek1017-s3/policy.py @@ -0,0 +1,124 @@ +"""Control policy for the dual-sphere reach task. + +The robot must touch the red sphere with its left hand and the green sphere +with its right hand at the same time. The only view of the scene is the +robot-mounted cameras, so the policy is a hand-written visual servo: + +* each wrist camera looks along its hand; the target sphere is found by colour + (red for the left wrist camera, green for the right one), +* a proportional controller drives the sphere to the optical centre of the + wrist image by adjusting shoulder pitch (vertical) and shoulder roll + (horizontal), +* the base walks forward while the spheres are still small, and stops as soon + as both spheres are large in the wrist images (the hands are then close), +* the servo then keeps both spheres centred and large, which keeps the hands + on the spheres until the task condition has held long enough to succeed. + +Deterministic: no randomness, no wall clock. +""" + +import cv2 +import numpy as np + + +# --- HSV colour segmentation for the two target spheres --------------------- +RED_LO = np.array([0, 110, 15], np.uint8) +RED_HI = np.array([12, 255, 255], np.uint8) +RED2_LO = np.array([168, 110, 15], np.uint8) +RED2_HI = np.array([180, 255, 255], np.uint8) +GRN_LO = np.array([33, 90, 15], np.uint8) +GRN_HI = np.array([85, 255, 255], np.uint8) + +CENTER = 42.0 + + +def _blob(image, colour): + """Return (u, v, area) of the target sphere in an RGB wrist image.""" + hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) + if colour == "red": + mask = cv2.inRange(hsv, RED_LO, RED_HI) | cv2.inRange(hsv, RED2_LO, RED2_HI) + else: + mask = cv2.inRange(hsv, GRN_LO, GRN_HI) + area = int(cv2.countNonZero(mask)) + if area < 15: + return None + m = cv2.moments(mask, binaryImage=True) + if m["m00"] <= 0: + return None + return (m["m10"] / m["m00"], m["m01"] / m["m00"], area) + + +class Policy: + """Visual-servo policy for the two-sphere reach task.""" + + GAIN = 0.0015 # rad per pixel of wrist-image error + MAX_STEP = 0.02 # rad per control step + WALK_SPEED = 0.10 + CLOSE_AREA = 3000.0 # both spheres this large -> hands are close + MAX_X = 0.16 # never walk further than this + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float64) + self.left = np.array([-0.20, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) + self.right = np.array([-0.20, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) + self.walking = True + self.stop_t = None + + def act(self, obs, tools): + ld = np.asarray(obs["low_dim_obs"], dtype=np.float64) + yaw = float(ld[21]) + x = float(ld[18]) + + bl = _blob(tools.image("left_wrist"), "red") + br = _blob(tools.image("right_wrist"), "green") + + if bl is not None: + u, v, _ = bl + self.left[0] += float( + np.clip(self.GAIN * (v - CENTER), -self.MAX_STEP, self.MAX_STEP) + ) + self.left[1] += float( + np.clip(self.GAIN * (CENTER - u), -self.MAX_STEP, self.MAX_STEP) + ) + if br is not None: + u, v, _ = br + self.right[0] += float( + np.clip(self.GAIN * (v - CENTER), -self.MAX_STEP, self.MAX_STEP) + ) + self.right[1] += float( + np.clip(self.GAIN * (CENTER - u), -self.MAX_STEP, self.MAX_STEP) + ) + + self.left[0] = float(np.clip(self.left[0], -1.6, 0.9)) + self.right[0] = float(np.clip(self.right[0], -1.6, 0.9)) + self.left[1] = float(np.clip(self.left[1], -1.0, 1.0)) + self.right[1] = float(np.clip(self.right[1], -1.0, 1.0)) + + both_close = ( + bl is not None + and br is not None + and bl[2] > self.CLOSE_AREA + and br[2] > self.CLOSE_AREA + ) + if self.walking and (both_close or x > self.MAX_X): + self.walking = False + self.stop_t = int(obs["t"]) + + if self.walking: + vx = self.WALK_SPEED + elif self.stop_t is not None and int(obs["t"]) - self.stop_t < 130: + # slow creep deeper while the wrist cameras still see both spheres + vx = 0.06 if (bl is not None and br is not None) else 0.0 + else: + vx = 0.0 + wz = float(np.clip(-2.0 * yaw, -0.4, 0.4)) if vx != 0.0 else 0.0 + + raw = self.hold.copy() + raw[0] = vx + raw[1] = 0.0 + raw[2] = 0.74 + raw[3] = wz + raw[4:11] = self.left + raw[11:18] = self.right + self.hold = raw.copy() + return raw diff --git a/policies/reach_target_dual/gpt61sol-s1/episodes.csv b/policies/reach_target_dual/gpt61sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..419c064bdd17d0c7a6c6578a0d5fb3243a0eefa9 --- /dev/null +++ b/policies/reach_target_dual/gpt61sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,277,success,0 +620001,1,252,success,0 +620002,1,374,success,0 +620003,1,306,success,0 +620004,1,195,success,0 +620005,0,700,timeout,0 +620006,1,275,success,0 +620007,0,700,timeout,0 +620008,1,240,success,0 +620009,1,310,success,0 +620010,1,192,success,0 +620011,1,247,success,0 +620012,1,223,success,0 +620013,0,700,timeout,0 +620014,1,285,success,0 +620015,1,358,success,0 +620016,1,387,success,0 +620017,1,386,success,0 +620018,1,386,success,0 +620019,1,249,success,0 +620020,1,260,success,0 +620021,1,362,success,0 +620022,1,502,success,0 +620023,1,287,success,0 +620024,1,242,success,0 +620025,1,438,success,0 +620026,1,245,success,0 +620027,1,450,success,0 +620028,1,334,success,0 +620029,1,323,success,0 +620030,0,700,timeout,0 +620031,1,286,success,0 +620032,1,245,success,0 +620033,1,342,success,0 +620034,1,327,success,0 +620035,0,700,timeout,0 +620036,1,251,success,0 +620037,1,266,success,0 +620038,1,277,success,0 +620039,1,279,success,0 +620040,1,258,success,0 +620041,1,226,success,0 +620042,1,204,success,0 +620043,1,315,success,0 +620044,1,290,success,0 +620045,1,414,success,0 +620046,1,342,success,0 +620047,0,700,timeout,0 +620048,1,231,success,0 +620049,1,319,success,0 +620050,1,295,success,0 +620051,1,378,success,0 +620052,1,248,success,0 +620053,0,700,timeout,0 +620054,1,318,success,0 +620055,0,700,timeout,0 +620056,1,284,success,0 +620057,0,700,timeout,0 +620058,1,273,success,0 +620059,0,700,timeout,0 +620060,1,302,success,0 +620061,0,700,timeout,0 +620062,1,224,success,0 +620063,1,237,success,0 +620064,1,699,success,0 +620065,0,700,timeout,0 +620066,1,213,success,0 +620067,0,700,timeout,0 +620068,1,306,success,0 +620069,0,700,timeout,0 +620070,0,700,timeout,0 +620071,1,209,success,0 +620072,1,594,success,0 +620073,1,204,success,0 +620074,1,323,success,0 +620075,0,700,timeout,0 +620076,1,239,success,0 +620077,1,318,success,0 +620078,1,228,success,0 +620079,1,367,success,0 +620080,1,331,success,0 +620081,1,200,success,0 +620082,1,207,success,0 +620083,1,206,success,0 +620084,1,378,success,0 +620085,1,228,success,0 +620086,1,330,success,0 +620087,0,700,timeout,0 +620088,1,378,success,0 +620089,1,338,success,0 +620090,1,216,success,0 +620091,1,332,success,0 +620092,1,279,success,0 +620093,0,700,timeout,0 +620094,1,229,success,0 +620095,1,214,success,0 +620096,1,263,success,0 +620097,1,562,success,0 +620098,1,307,success,0 +620099,1,248,success,0 diff --git a/policies/reach_target_dual/gpt61sol-s1/policy.py b/policies/reach_target_dual/gpt61sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a98f7564a361bdb57dbdd1c39c83327d316ffe28 --- /dev/null +++ b/policies/reach_target_dual/gpt61sol-s1/policy.py @@ -0,0 +1,170 @@ +"""Hand-written, deterministic visual servoing for simultaneous two-hand reaching. + +Uses only the three robot cameras and proprioception. Color segmentation tracks +the spheres; image feedback aligns each hand, and contact color holds the reach. +A late recovery retries a previously observed contact pose. No learned models, +seed-specific placements, demonstration files, or wall-clock time are used.""" +import cv2 +import numpy as np + +def sphere(im, green=False): + """Locate the largest target-colored component and its contact highlight.""" + a = im.astype(np.int16) + r, g, b = (a[:, :, 0], a[:, :, 1], a[:, :, 2]) + m = (g > 1.5 * r) & (g > 1.4 * b) & (g > 35) if green else (r > 1.6 * g) & (r > 1.6 * b) & (r > 45) + n, labels, stats, cent = cv2.connectedComponentsWithStats(m.astype(np.uint8)) + if n < 2: + return None + k = 1 + np.argmax(stats[1:, 4]) + x, y, w, h, area = stats[k] + cx, cy = cent[k] + rad = max(w, h) / 2 + if x == 0: + cx = x + w - rad + if x + w >= 84: + cx = x + rad + if y == 0: + cy = y + h - rad + if y + h >= 84: + cy = y + rad + val = (g if green else r)[labels == k] + bright = bool(np.count_nonzero(val > 230) > min(8, area * 0.2)) + return (np.array([cx, cy]), bright, area) + +def tip(im, side): + """Estimate the visible fingertips from the bright neutral hand surfaces.""" + a = im.astype(np.int16) + m = (a.min(2) > 155) & (a.max(2) - a.min(2) < 35) + if side == 0: + m[:, 42:] = False + else: + m[:, :42] = False + m[75:] = False + ys, xs = np.where(m) + if len(xs) < 3: + return None + top = ys.min() + sel = ys < top + 11 + return np.array([np.median(xs[sel]), top + 1.5]) + +class Policy: + """Close the base loop at 50 Hz and update visual arm feedback at 12.5 Hz.""" + + def reset(self, obs, tools): + """Initialize the stance, image history, and independent contact states.""" + self.a = np.asarray(tools.hold_action(), dtype=float) + self.a[18:] = 0.6 + self.a[4:18] = 0 + self.hit = [False, False] + self.cool = [0, 0] + self.last_h = [None, None] + self.last_hp = [None, None] + self.freeze = False + self.freeze_t = 0 + self.contact_q = [None, None] + self.turn = 0.0 + self.freeze_yaw = 0.0 + self.start = np.asarray(obs['low_dim_obs'][18:22], float) + self.base_x = self.start[0] + + def act(self, obs, tools): + """Approach gently, align the hands, and hold both confirmed reaches.""" + t = obs['t'] + ld = obs['low_dim_obs'] + self.a[:2] = 0 + self.a[3] = np.clip(-ld[21] * 3, -0.25, 0.25) + if t % 4 == 0: + im = tools.image('head') + balls = [sphere(im, False), sphere(im, True)] + for si in range(2): + if balls[si] is not None: + self.last_h[si] = balls[si][0].copy() + self.last_hp[si] = ld[18:22].copy() + elif self.last_h[si] is None: + self.last_h[si] = np.array([-5.0, 10.0] if si == 0 else [89.0, 8.0]) + self.last_hp[si] = ld[18:22].copy() + tips = [tip(im, 0), tip(im, 1)] + for side in range(2): + s = balls[side] + w = sphere(tools.image('left_wrist' if side == 0 else 'right_wrist'), side == 1) + if s is not None and s[1] or (w is not None and w[1]): + self.hit[side] = True + self.contact_q[side] = (ld[:7] if side == 0 else ld[9:16]).copy() + if not self.freeze: + self.base_x = float(ld[18]) + self.freeze_t = t + self.freeze_yaw = float(ld[21]) + self.freeze = True + self.cool[side] = t + 16 + elif self.hit[side]: + self.hit[side] = False + idx = 4 + side * 7 + if not self.hit[side] and t >= self.cool[side]: + visible = s is not None and tips[side] is not None and (t < 612 or tips[side][1] < 65) + if visible: + err = s[0] + [0, 4 if t < 612 else -4] - tips[side] + self.a[idx] += np.clip(0.004 * err[1], -0.018, 0.018) + ex = err[0] + else: + predicted = self.last_h[side].copy() + delta = ld[18:22] - self.last_hp[side] + predicted[0] = 42 + (predicted[0] - 42) * (1 + delta[0] * 0.8) + predicted[1] += delta[0] * 130 + predicted_tip = np.array([18.0 if side == 0 else 69.0, 33.0]) + predicted_tip[0] -= 60 * self.a[idx + 1] + 35 * self.a[idx + 2] + predicted_tip[1] += 65 * self.a[idx] + 40 * self.a[idx + 3] + if tips[side] is not None and (t < 612 or tips[side][1] < 65): + predicted_tip = tips[side] + err = predicted + [0, 4 if t < 612 else -4] - predicted_tip + ex = err[0] + self.a[idx] += np.clip(0.003 * err[1], -0.015, 0.015) + if w is not None: + self.a[idx] += np.clip(0.001 * (w[0][1] - 55), -0.008, 0.008) + if w is not None and w[2] > 10: + ex = (w[0][0] - (42 if t < 612 else 62)) * 0.6 + self.a[idx + 1] += np.clip(-0.003 * ex, -0.012, 0.012) + self.a[idx] = np.clip(self.a[idx], -1.4, 0.7) + self.a[idx + 1] = np.clip(self.a[idx + 1], -0.55, 0.55) + q = ld[0:7] if side == 0 else ld[9:16] + if abs(self.a[idx + 1] - q[1]) > 0.05: + self.a[idx + 2] += np.clip(-0.002 * ex, -0.008, 0.008) + self.a[idx + 2] = np.clip(self.a[idx + 2], -0.6, 0.6) + if t > 50 and (not self.freeze): + self.base_x = min(self.start[0] + 0.4, self.base_x + 0.008) + if self.freeze and t > self.freeze_t + 60: + for side in range(2): + if not self.hit[side] and (t < 612 or t >= self.cool[side]): + idx = 4 + 7 * side + new_e = min(1.25, self.a[idx + 3] + 0.014) + if t >= 612 and self.a[idx + 3] > 0.85: + new_e = max(0.85, self.a[idx + 3] - 0.02) + old_e = self.a[idx + 3] + self.a[idx + 3] = new_e + self.a[idx] -= 0.6 * (new_e - old_e) + self.turn = 0.0 + if self.freeze and t >= 612: + for side in range(2): + s = balls[side] + if not self.hit[side] and (s is None or (s[0][0] < 8 if side == 0 else s[0][0] > 76)): + direction = 1.0 if side == 0 else -1.0 + if direction * (float(ld[21]) - self.freeze_yaw) < 0.3: + self.turn = direction * 0.15 + break + if t == 612: + for side in range(2): + if not self.hit[side] and self.contact_q[side] is not None: + idx = 4 + side * 7 + self.a[idx:idx + 7] = self.contact_q[side] + self.a[idx] -= 0.03 + self.a[idx + 3] -= 0.025 + self.a[idx + 4:idx + 7] = 0 + self.cool[side] = t + 50 + if self.freeze: + self.a[:2] = 0 + self.a[3] = self.turn + return self.a.copy() + dx = self.base_x - ld[18] + dy = self.start[1] - ld[19] + self.a[0] = 0 if abs(dx) < 0.012 else np.sign(dx) * max(0.065, min(0.15, abs(dx) * 2)) + self.a[1] = 0 if abs(dy) < 0.012 else np.sign(dy) * max(0.065, min(0.15, abs(dy) * 2)) + return self.a.copy() diff --git a/policies/reach_target_dual/gpt61sol-s2/episodes.csv b/policies/reach_target_dual/gpt61sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..72d1925c10eac4ad1bd4050f2d3d2a2066c79d65 --- /dev/null +++ b/policies/reach_target_dual/gpt61sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,357,success,0 +620001,1,569,success,0 +620002,0,700,timeout,0 +620003,1,174,success,0 +620004,1,175,success,0 +620005,0,700,timeout,0 +620006,0,700,timeout,0 +620007,1,539,success,0 +620008,1,628,success,0 +620009,1,205,success,0 +620010,1,182,success,0 +620011,1,176,success,0 +620012,1,390,success,0 +620013,0,700,timeout,0 +620014,0,700,timeout,0 +620015,1,316,success,0 +620016,0,700,timeout,0 +620017,0,700,timeout,0 +620018,0,700,timeout,0 +620019,1,570,success,0 +620020,1,352,success,0 +620021,1,178,success,0 +620022,0,700,timeout,0 +620023,1,432,success,0 +620024,1,363,success,0 +620025,0,700,timeout,0 +620026,1,358,success,0 +620027,0,700,timeout,0 +620028,0,700,timeout,0 +620029,0,700,timeout,0 +620030,0,700,timeout,0 +620031,0,700,timeout,0 +620032,0,700,timeout,0 +620033,0,700,timeout,0 +620034,0,700,timeout,0 +620035,1,366,success,0 +620036,0,700,timeout,0 +620037,1,397,success,0 +620038,0,700,timeout,0 +620039,1,360,success,0 +620040,1,351,success,0 +620041,1,674,success,0 +620042,1,177,success,0 +620043,1,576,success,0 +620044,1,467,success,0 +620045,1,673,success,0 +620046,1,206,success,0 +620047,1,358,success,0 +620048,1,185,success,0 +620049,1,323,success,0 +620050,1,357,success,0 +620051,0,700,timeout,0 +620052,1,359,success,0 +620053,1,401,success,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,1,398,success,0 +620058,1,328,success,0 +620059,0,700,timeout,0 +620060,1,567,success,0 +620061,0,700,timeout,0 +620062,1,262,success,0 +620063,1,255,success,0 +620064,1,385,success,0 +620065,0,700,timeout,0 +620066,1,336,success,0 +620067,0,700,timeout,0 +620068,1,326,success,0 +620069,1,360,success,0 +620070,1,377,success,0 +620071,1,228,success,0 +620072,0,700,timeout,0 +620073,1,175,success,0 +620074,0,700,timeout,0 +620075,1,328,success,0 +620076,1,567,success,0 +620077,0,700,timeout,0 +620078,0,700,timeout,0 +620079,0,700,timeout,0 +620080,0,700,timeout,0 +620081,1,207,success,0 +620082,1,202,success,0 +620083,1,224,success,0 +620084,0,700,timeout,0 +620085,1,395,success,0 +620086,0,700,timeout,0 +620087,1,359,success,0 +620088,0,700,timeout,0 +620089,0,700,timeout,0 +620090,1,231,success,0 +620091,1,639,success,0 +620092,1,392,success,0 +620093,0,700,timeout,0 +620094,1,209,success,0 +620095,1,568,success,0 +620096,1,243,success,0 +620097,1,564,success,0 +620098,1,179,success,0 +620099,1,209,success,0 diff --git a/policies/reach_target_dual/gpt61sol-s2/policy.py b/policies/reach_target_dual/gpt61sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..0495d8faf57d1e6a1e4a0f382c2e164440f869eb --- /dev/null +++ b/policies/reach_target_dual/gpt61sol-s2/policy.py @@ -0,0 +1,140 @@ +"""Colour perception and deterministic arm pattern search, with base feedback.""" +import cv2 +import numpy as np + +def sphere(im, side): + f=im.astype(float);v=f[:,:,side] + m=((v>35)&(v>1.65*f[:,:,(side+1)%3])&(v>1.65*f[:,:,(side+2)%3])).astype('uint8') + cs,_=cv2.findContours(m,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) + if not cs:return None + c=max(cs,key=cv2.contourArea).reshape(-1,2) + if len(c)<8:return None + x,y,w,h=cv2.boundingRect(c);bright=float(v[m!=0].max()) + # A sphere's silhouette is a circle of rays on the viewing unit sphere. + # Its plane's distance from the origin is cos(angular radius). + edge=c[(c[:,0]>1)&(c[:,0]<82)&(c[:,1]>1)&(c[:,1]<82)] + dist=20.;pos=np.array([0.,0.,20.]) + if len(edge)>=12: + rays=np.column_stack(((edge.astype(float)-41.5)/55.,np.ones(len(edge)))) + rays/=np.linalg.norm(rays,axis=1)[:,None] + mean=rays.mean(axis=0);_,_,vh=np.linalg.svd(rays-mean,full_matrices=False) + n=vh[-1] + if n[2]<0:n=-n + co=abs(n@mean);dist=1/np.sqrt(max(1-co*co,.001));pos=n*dist + return np.array([x+w/2,y+h/2,(w+h)/4,bright,dist,*pos]) + +class Policy: + """Image-based reaching with bounded, deterministic joint pattern search. + + All geometry comes from the three permitted cameras. No demonstration, + seed table, fitted control model, or external scene state is used. + """ + + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=float) + self.a[18:] = 0.0 + self.a[4:11] = [-.2, .35, 0, 0, 0, 0, 0] + self.a[11:18] = [-.3, -.25, 0, 0, 0, 0, 0] + head = tools.image('head') + self.states = [] + for side in range(2): + z = sphere(head, side) + inner = False + k = 4 + 7 * side + if z is not None: + self.a[k] = np.clip((z[1] - 29) / 75., -.48, .18) + center = 30 if side == 0 else 54 + self.a[k + 1] = np.clip( + (center - z[0]) * .012, + .08 if side == 0 else -.65, + .65 if side == 0 else -.06, + ) + inner = z[0] > 18 if side == 0 else z[0] < 66 + ids = [0, 1, 6, 2, 3, 4, 5] if inner else [0, 1, 6, 2, 3, 5] + deltas = [.16, .2, .3, .3, .25, .3, .25] if inner else [.16, .2, .3, .3, .25, .25] + self.states.append(dict( + inner=inner, ids=ids, deltas=deltas, + coord=0, trial=0, cycle=0, hit=False, + best=self.a[k:k + 7].copy(), cost=30., + )) + self.phase = 'walk' + self.start = 0 + self.lower = np.tile([-2, -1, -1.4, -.9, -1, -1.4, -1.4], 2) + self.upper = np.tile([1, 1, 1.4, 1.6, 1, 1.4, 1.4], 2) + + @staticmethod + def score(z, inner): + if z is None: + return 50. + if z[3] > 220: + return .01 + target = [0, .3, 1.7] if inner else [0, 0, 1.5] + return float(np.linalg.norm(z[5:8] - target)) + + def act(self, obs, tools): + t = obs['t'] + q = obs['low_dim_obs'] + a = self.a + if self.phase == 'walk': + a[0] = .12 if q[18] < .075 and t < 160 else 0 + a[3] = np.clip(-3 * q[21], -.3, .3) + a[1] = .06 if q[19] < -.02 else (-.06 if q[19] > .02 else 0) + if a[0] == 0: + a[:2] = 0 + a[3] = 0 + self.phase = 'search' + self.start = t + 35 + for side, state in enumerate(self.states): + k = 4 + 7 * side + state['best'] = a[k:k + 7].copy() + return a.copy() + + if t < self.start or (t - self.start) % 12: + return a.copy() + + head = tools.image('head') + for side, camera in enumerate(('left_wrist', 'right_wrist')): + state = self.states[side] + k = 4 + 7 * side + z = sphere(tools.image(camera), side) + head_z = sphere(head, side) + active = ((z is not None and z[3] > 220) or + (head_z is not None and head_z[3] > 220)) + cost = self.score(z, state['inner']) + if active: + state['hit'] = True + state['best'] = a[k:k + 7].copy() + state['cost'] = .8 + elif state['hit']: + state['hit'] = False + state['cost'] = cost + if not state['hit'] and cost < state['cost']: + state['cost'] = cost + state['best'] = a[k:k + 7].copy() + + a[k:k + 7] = state['best'] + if state['trial'] == 0: + state['cost'] = cost + if state['trial'] < 2: + sign = 1 if state['trial'] == 0 else -1 + coord = state['coord'] + joint = state['ids'][coord] + delta = state['deltas'][coord] * (.85 ** state['cycle']) + if not state['hit']: + a[k + joint] += sign * delta + # Counter-rotate the wrist when bending the inner arm. + # This keeps the target visible during the positional search. + if state['inner'] and joint == 2: + a[k + 6] -= sign * delta + if state['inner'] and joint == 3: + a[k] -= .55 * sign * delta + a[k + 5] -= sign * delta + state['trial'] += 1 + else: + state['trial'] = 0 + state['coord'] += 1 + if state['coord'] == len(state['ids']): + state['coord'] = 0 + state['cycle'] += 1 + a[4:18] = np.clip(a[4:18], self.lower, self.upper) + return a.copy() diff --git a/policies/reach_target_dual/gpt61sol-s3/episodes.csv b/policies/reach_target_dual/gpt61sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..4d8095e37cca11216db03ba428dd585074356b46 --- /dev/null +++ b/policies/reach_target_dual/gpt61sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,700,timeout,0 +620001,1,399,success,0 +620002,1,257,success,0 +620003,1,352,success,0 +620004,1,232,success,0 +620005,1,451,success,0 +620006,0,700,timeout,0 +620007,0,700,timeout,0 +620008,0,700,timeout,0 +620009,1,367,success,0 +620010,1,192,success,0 +620011,1,311,success,0 +620012,1,354,success,0 +620013,0,700,timeout,0 +620014,1,283,success,0 +620015,1,387,success,0 +620016,1,451,success,0 +620017,1,496,success,0 +620018,0,700,timeout,0 +620019,1,407,success,0 +620020,1,399,success,0 +620021,0,700,timeout,0 +620022,1,630,success,0 +620023,0,700,timeout,0 +620024,1,312,success,0 +620025,0,700,timeout,0 +620026,1,244,success,0 +620027,1,463,success,0 +620028,1,490,success,0 +620029,1,468,success,0 +620030,1,395,success,0 +620031,0,700,timeout,0 +620032,1,252,success,0 +620033,1,631,success,0 +620034,1,300,success,0 +620035,1,343,success,0 +620036,1,499,success,0 +620037,1,332,success,0 +620038,1,388,success,0 +620039,1,308,success,0 +620040,1,364,success,0 +620041,1,411,success,0 +620042,1,208,success,0 +620043,0,700,timeout,0 +620044,1,320,success,0 +620045,1,410,success,0 +620046,1,311,success,0 +620047,1,313,success,0 +620048,1,462,success,0 +620049,1,481,success,0 +620050,0,700,timeout,0 +620051,1,495,success,0 +620052,0,700,timeout,0 +620053,0,700,timeout,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,1,260,success,0 +620058,0,700,timeout,0 +620059,1,265,success,0 +620060,1,338,success,0 +620061,1,354,success,0 +620062,1,237,success,0 +620063,1,312,success,0 +620064,1,339,success,0 +620065,0,700,timeout,0 +620066,0,700,timeout,0 +620067,0,700,timeout,0 +620068,1,310,success,0 +620069,0,700,timeout,0 +620070,0,700,timeout,0 +620071,0,700,timeout,0 +620072,0,700,timeout,0 +620073,1,330,success,0 +620074,1,338,success,0 +620075,0,700,timeout,0 +620076,1,334,success,0 +620077,1,271,success,0 +620078,1,249,success,0 +620079,1,372,success,0 +620080,1,395,success,0 +620081,1,299,success,0 +620082,1,268,success,0 +620083,1,314,success,0 +620084,0,700,timeout,0 +620085,1,349,success,0 +620086,0,700,timeout,0 +620087,0,700,timeout,0 +620088,1,639,success,0 +620089,0,700,timeout,0 +620090,1,323,success,0 +620091,1,421,success,0 +620092,1,381,success,0 +620093,0,700,timeout,0 +620094,0,700,timeout,0 +620095,1,317,success,0 +620096,1,339,success,0 +620097,0,700,timeout,0 +620098,0,700,timeout,0 +620099,1,305,success,0 diff --git a/policies/reach_target_dual/gpt61sol-s3/policy.py b/policies/reach_target_dual/gpt61sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..515412a0b5702d9ddcd32cd36922aa84823fc3ae --- /dev/null +++ b/policies/reach_target_dual/gpt61sol-s3/policy.py @@ -0,0 +1,113 @@ +# Deterministic image feedback for simultaneous two-hand contact. +# Runtime inputs are only robot cameras and proprioception. +import numpy as np +import cv2 + +def sphere(im, side): + c = im[:, :, side].astype(float) + other = im[:, :, 1 - side].astype(float) + m = ((c > 55) & (c > other * 1.6) & (c > im[:, :, 2] * 1.5)).astype('uint8') + n, l, st, ct = cv2.connectedComponentsWithStats(m) + if n < 2: + return None + i = 1 + np.argmax(st[1:, 4]) + pix = im[:, :, side][l == i] + return (ct[i], float(np.max(pix)), st[i, 4]) + +def hand(im, side): + a = im.astype(float) + m = (a.min(2) > 130) & (a.max(2) - a.min(2) < 65) + m[70:] = False + if side == 0: + m[:, 42:] = False + else: + m[:, :42] = False + ys, xs = np.where(m) + if len(ys) < 5: + return None + y = ys.min() + idx = ys < y + 4 + return np.array([np.median(xs[idx]), y + 8.0]) + +class Policy: + + def reset(self, obs, tools): + self.a = np.array(tools.hold_action()) + self.a[18:] = 0.6 + self.q = np.zeros((2, 7)) + self.lock = [False, False] + self.anchor = [None, None] + self.miss = [0, 0] + self.search = [0, 0] + self.phase = 0 + self.stop = 0 + self.target = [None, None] + + def act(self, obs, tools): + t = obs['t'] + # Refresh vision every four steps and hold commands in between. + if t % 4 == 0: + im = tools.image('head') + ss = [sphere(im, s) for s in range(2)] + if self.phase == 0: + visible = [s for s in ss if s is not None and s[2] >= 10] + if visible: + center = np.mean([s[0] for s in visible], axis=0) + self.a[0] = 0.12 if center[1] < 31 else 0 + self.a[1] = np.clip((42 - center[0]) * 0.01, -0.12, 0.12) if len(visible) == 2 else 0 + if abs(self.a[1]) < 0.06: + self.a[1] = 0 + if center[1] >= 31: + self.a[:2] = 0 + self.phase = 1 + self.stop = t + else: + self.a[0] = 0.1 + # Let the walking controller settle before arm alignment. + if self.phase == 1 and t >= self.stop + 32: + self.phase = 2 + self.target = [s[0].copy() if s is not None else np.array([0 if side == 0 else 83, 20]) for side, s in enumerate(ss)] + if self.phase == 2: + for side, s in enumerate(ss): + h = hand(im, side) + wrist = sphere(tools.image('left_wrist' if side == 0 else 'right_wrist'), side) if s is None or s[2] < 12 else None + touching = s is not None and s[1] > 220 or (wrist is not None and wrist[1] > 220) + if touching: + # Capture measured joint positions to avoid target overshoot. + if self.anchor[side] is None: + start = 0 if side == 0 else 9 + actual = np.array(obs['low_dim_obs'][start:start + 7], float) + actual[0] -= 0.025 + actual[3] -= 0.022 + actual[5] = 0 + self.q[side] = actual + self.anchor[side] = actual.copy() + self.miss[side] = 0 + elif self.anchor[side] is not None: + self.miss[side] += 1 + self.lock[side] = self.anchor[side] is not None + if self.lock[side] and self.miss[side] >= 8 and (self.miss[side] % 4 == 0): + k = self.search[side] + self.search[side] += 1 + offset = np.zeros(7) + axis = [0, 1, 3][k // 2 % 3] + amplitude = [0.035, 0.05, 0.07][k // 2 % 3] * (1 + k // 12) + offset[axis] = amplitude * (1 if k % 2 == 0 else -1) + self.q[side] = self.anchor[side] + offset + # Align the hand in the head view while sweeping reach depth. + if not self.lock[side]: + elbow = min(1.5, max(0, t - self.stop - 100) * 0.003) + if h is None: + self.q[side, 0] -= 0.62 * (elbow - self.q[side, 3]) + self.q[side, 3] = elbow + if s is not None and s[2] > 75: + self.target[side] = 0.85 * self.target[side] + 0.15 * s[0] + if h is not None: + err = self.target[side] - h + self.q[side, 0] += np.clip(err[1] * 0.003, -0.025, 0.025) + self.q[side, 1] -= np.clip(err[0] * 0.006, -0.025, 0.025) + self.q[side, 0] = np.clip(self.q[side, 0], -2.0, 0.5) + self.q[side, 1] = np.clip(self.q[side, 1], -0.8, 0.8) + self.a[4:11] = self.q[0] + self.a[11:18] = self.q[1] + return self.a.copy() diff --git a/policies/reach_target_dual/gpt61terra-s1/episodes.csv b/policies/reach_target_dual/gpt61terra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..a76a0e37518bddf0590c0ba2411e616710842a35 --- /dev/null +++ b/policies/reach_target_dual/gpt61terra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,182,success,0 +620001,1,166,success,0 +620002,1,566,success,0 +620003,1,133,success,0 +620004,1,121,success,0 +620005,0,700,timeout,0 +620006,1,182,success,0 +620007,1,120,success,0 +620008,1,134,success,0 +620009,1,296,success,0 +620010,1,120,success,0 +620011,1,120,success,0 +620012,1,121,success,0 +620013,0,700,timeout,0 +620014,1,178,success,0 +620015,0,700,timeout,0 +620016,0,700,timeout,0 +620017,0,700,timeout,0 +620018,0,700,timeout,0 +620019,1,159,success,0 +620020,1,122,success,0 +620021,0,700,timeout,0 +620022,0,700,timeout,0 +620023,0,700,timeout,0 +620024,1,564,success,0 +620025,0,700,timeout,0 +620026,1,130,success,0 +620027,0,700,timeout,0 +620028,1,568,success,0 +620029,1,185,success,0 +620030,1,648,success,0 +620031,0,700,timeout,0 +620032,1,232,success,0 +620033,0,700,timeout,0 +620034,1,565,success,0 +620035,1,141,success,0 +620036,1,123,success,0 +620037,1,190,success,0 +620038,1,238,success,0 +620039,1,634,success,0 +620040,1,365,success,0 +620041,1,183,success,0 +620042,1,120,success,0 +620043,1,518,success,0 +620044,1,176,success,0 +620045,0,700,timeout,0 +620046,0,700,timeout,0 +620047,1,121,success,0 +620048,0,700,timeout,0 +620049,1,184,success,0 +620050,1,243,success,0 +620051,0,700,timeout,0 +620052,0,700,timeout,0 +620053,1,133,success,0 +620054,0,700,timeout,0 +620055,1,570,success,0 +620056,0,700,timeout,0 +620057,0,700,timeout,0 +620058,1,121,success,0 +620059,1,599,success,0 +620060,1,131,success,0 +620061,1,539,success,0 +620062,1,523,success,0 +620063,1,122,success,0 +620064,1,132,success,0 +620065,0,700,timeout,0 +620066,1,210,success,0 +620067,0,700,timeout,0 +620068,1,207,success,0 +620069,1,248,success,0 +620070,1,240,success,0 +620071,0,700,timeout,0 +620072,1,567,success,0 +620073,1,121,success,0 +620074,1,340,success,0 +620075,0,700,timeout,0 +620076,1,185,success,0 +620077,1,570,success,0 +620078,1,508,success,0 +620079,1,244,success,0 +620080,0,700,timeout,0 +620081,1,129,success,0 +620082,1,121,success,0 +620083,1,121,success,0 +620084,0,700,timeout,0 +620085,1,365,success,0 +620086,0,700,timeout,0 +620087,0,700,timeout,0 +620088,0,700,timeout,0 +620089,0,700,timeout,0 +620090,1,130,success,0 +620091,1,692,success,0 +620092,1,565,success,0 +620093,0,700,timeout,0 +620094,1,121,success,0 +620095,1,244,success,0 +620096,1,121,success,0 +620097,1,185,success,0 +620098,0,700,timeout,0 +620099,1,123,success,0 diff --git a/policies/reach_target_dual/gpt61terra-s1/policy.py b/policies/reach_target_dual/gpt61terra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..bf39059079869f55ddcfb7a5402a3d2bfe9a1eb8 --- /dev/null +++ b/policies/reach_target_dual/gpt61terra-s1/policy.py @@ -0,0 +1,54 @@ +import numpy as np +import cv2 +class Policy: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action(),dtype=np.float32);self.x0=float(obs['low_dim_obs'][18]);self.phase=0;self.start=0;self.second=False + hsv=cv2.cvtColor(tools.image('head'),cv2.COLOR_RGB2HSV);self.xy=[] + for lo,hi,default in [((0,100,45),(8,255,255),(15,15)),((40,100,45),(85,255,255),(70,15))]: + mask=cv2.inRange(hsv,np.array(lo),np.array(hi)); yy,xx=np.where(mask>0) + if len(xx)>3: + x=float(xx.mean());y=float(yy.mean()) + if x<6:x-=3 + if x>78:x+=3 + if y<6:y-=3 + self.xy.append((x,y)) + else:self.xy.append(default) + red,green=self.xy + self.p=[np.clip(-.3+(red[1]-12.6)*.012,-.65,.05),np.clip(-.3+(green[1]-17.7)*.012,-.65,.05)] + self.y=[np.clip((25-red[0])*.014,-.4,.5),np.clip(-.2+(72-green[0])*.014,-.5,.4)] + self.lock=[None,None];self.missing=[0,0] + self.offsets=[(0,0),(.08,0),(-.08,0),(0,.10),(0,-.10),(.16,0),(-.16,0),(.08,.10),(.08,-.10),(-.08,.10),(-.08,-.10),(.16,.10),(.16,-.10),(-.16,.10),(-.16,-.10),(.24,0),(-.24,0),(.24,.1),(.24,-.1),(-.24,.1),(-.24,-.1), (0,.2),(0,-.2),(.12,.2),(.12,-.2),(-.12,.2),(-.12,-.2)] + def act(self,obs,tools): + a=self.a.copy();t=obs['t'];x=float(obs['low_dim_obs'][18])-self.x0 + if self.phase==0: + if x<.12:a[0]=.15 + else:self.phase=1;self.start=t + if self.phase==1 and not self.second and t>=390: + self.phase=2;self.second=True;self.lock=[None,None];self.missing=[0,0] + if self.phase==2: + a[2]=.74 + if obs['low_dim_obs'][20]>.72: + if x<.16:a[0]=.12 + else:self.phase=1;self.start=t + if self.phase==1: + dt=t-self.start;ind=max(0,(dt-55)//20); dp,dy=self.offsets[min(ind,len(self.offsets)-1)] + a[2]=.65 + for j,idx in enumerate([4,11]): + a[idx:idx+4]=self.lock[j] if self.lock[j] is not None else [np.clip(self.p[j]+dp,-.8,.3),0,np.clip(self.y[j]+dy,-.6,.6),0] + if dt>=50 and dt%5==0: + ims=[tools.image('head'),tools.image('left_wrist'),tools.image('right_wrist')] + for j in range(2): + found=False + for im in [ims[0],ims[j+1]]: + ch=im[:,:,j];other=im[:,:,1-j];blue=im[:,:,2] + if np.count_nonzero((ch>225)&(other<40)&(blue<40))>25: + found=True + if self.lock[j] is None: + q=np.asarray(obs['low_dim_obs'][0:4] if j==0 else obs['low_dim_obs'][9:13],dtype=np.float32).copy() + q[0]-=.02;q[1]=0;q[3]=0 + self.lock[j]=q + break + if self.lock[j] is not None: + self.missing[j]=0 if found else self.missing[j]+1 + if self.missing[j]>=4:self.lock[j]=None;self.missing[j]=0 + return a diff --git a/policies/reach_target_dual/gpt61terra-s2/episodes.csv b/policies/reach_target_dual/gpt61terra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..b5c8ac365254cf8d8a1eceb7b89606fb93cf18ed --- /dev/null +++ b/policies/reach_target_dual/gpt61terra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,699,success,0 +620001,0,700,timeout,0 +620002,0,700,timeout,0 +620003,1,134,success,0 +620004,1,356,success,0 +620005,0,700,timeout,0 +620006,1,698,success,0 +620007,0,700,timeout,0 +620008,0,700,timeout,0 +620009,1,278,success,0 +620010,1,607,success,0 +620011,0,700,timeout,0 +620012,1,356,success,0 +620013,0,700,timeout,0 +620014,1,693,success,0 +620015,1,186,success,0 +620016,0,700,timeout,0 +620017,0,700,timeout,0 +620018,0,700,timeout,0 +620019,0,700,timeout,0 +620020,0,700,timeout,0 +620021,0,700,timeout,0 +620022,0,700,timeout,0 +620023,1,423,success,0 +620024,0,700,timeout,0 +620025,0,700,timeout,0 +620026,0,700,timeout,0 +620027,0,700,timeout,0 +620028,1,700,success,0 +620029,1,356,success,0 +620030,0,700,timeout,0 +620031,0,700,timeout,0 +620032,0,700,timeout,0 +620033,0,700,timeout,0 +620034,1,472,success,0 +620035,0,700,timeout,0 +620036,0,700,timeout,0 +620037,0,700,timeout,0 +620038,0,700,timeout,0 +620039,0,700,timeout,0 +620040,0,700,timeout,0 +620041,0,700,timeout,0 +620042,1,94,success,0 +620043,0,700,timeout,0 +620044,0,700,timeout,0 +620045,0,700,timeout,0 +620046,1,152,success,0 +620047,1,446,success,0 +620048,1,136,success,0 +620049,0,700,timeout,0 +620050,0,700,timeout,0 +620051,0,700,timeout,0 +620052,0,700,timeout,0 +620053,0,700,timeout,0 +620054,1,407,success,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,1,488,success,0 +620058,0,700,timeout,0 +620059,0,700,timeout,0 +620060,1,335,success,0 +620061,0,700,timeout,0 +620062,1,449,success,0 +620063,0,700,timeout,0 +620064,0,700,timeout,0 +620065,0,700,timeout,0 +620066,1,446,success,0 +620067,0,700,timeout,0 +620068,1,98,success,0 +620069,0,700,timeout,0 +620070,0,700,timeout,0 +620071,0,700,timeout,0 +620072,1,277,success,0 +620073,1,356,success,0 +620074,0,700,timeout,0 +620075,0,700,timeout,0 +620076,0,700,timeout,0 +620077,0,700,timeout,0 +620078,0,700,timeout,0 +620079,0,700,timeout,0 +620080,0,700,timeout,0 +620081,1,564,success,0 +620082,1,524,success,0 +620083,0,700,timeout,0 +620084,0,700,timeout,0 +620085,1,441,success,0 +620086,0,700,timeout,0 +620087,0,700,timeout,0 +620088,0,700,timeout,0 +620089,0,700,timeout,0 +620090,0,700,timeout,0 +620091,1,420,success,0 +620092,1,378,success,0 +620093,0,700,timeout,0 +620094,1,201,success,0 +620095,1,408,success,0 +620096,1,381,success,0 +620097,1,377,success,0 +620098,0,700,timeout,0 +620099,0,700,timeout,0 diff --git a/policies/reach_target_dual/gpt61terra-s2/policy.py b/policies/reach_target_dual/gpt61terra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..8b25676a9a039c0ea61dd2a8af180c7bebe04ae9 --- /dev/null +++ b/policies/reach_target_dual/gpt61terra-s2/policy.py @@ -0,0 +1,57 @@ +import numpy as np +import cv2 + +class Policy: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action(),dtype=np.float32) + self.x0=float(obs['low_dim_obs'][18]);self.phase=0;self.phase_t=0 + im=tools.image('head');hsv=cv2.cvtColor(im,cv2.COLOR_RGB2HSV);h,s,v=cv2.split(hsv) + self.guess=[];self.roll=[] + for i in range(2): + mask=(s>90)&(v>30)&(((h<10)|(h>170)) if i==0 else ((h>40)&(h<90))) + n,lab,stats,cent=cv2.connectedComponentsWithStats(mask.astype(np.uint8)) + if n>1: + k=1+np.argmax(stats[1:,4]); x,y=cent[k]; x0,y0,w,ht,area=stats[k] + if x0==0:x-=max(0,ht-w)*.45 + if x0+w>=84:x+=max(0,ht-w)*.45 + if y0==0:y-=max(0,w-ht)*.45 + else:x,y=(5 if i==0 else 79),15 + p=np.clip(-.45+(y-13)*.016,-1.1,.15) + dx=(25-x) if i==0 else (x-72) + self.roll.append(float(np.clip(dx*.007,-.12,.24))) + yaw=np.clip(dx*.007 if i==0 else .3+dx*.007,-.5,1.3) + self.guess.append((p,yaw)) + self.index=[0,0]; self.lock=[False,False];self.locktime=[0,0];self.poses=[None,None] + xy=[(0,0),(-.12,0),(.12,0),(0,-.16),(0,.16),(-.12,-.16),(-.12,.16),(.12,-.16),(.12,.16)] + self.offsets=[(dp,dy,el) for dp,dy in xy for el in (0,.3,.6)] + def act(self,obs,tools): + t=obs['t'];ld=obs['low_dim_obs'];a=self.a.copy() + if self.phase==0: + a[0]=.2 + if ld[18]>=self.x0+.06 or t>38:self.phase=1;self.phase_t=t;a[0]=0 + return a + a[2]=.62 + if self.phase==1 and t-self.phase_t>=45:self.phase=2;self.phase_t=t + if self.phase==2 and (t-self.phase_t)%3==0: + im=tools.image('head').astype(np.int16) + def mask(im,i): + im=im.astype(np.int16) + return ((im[:,:,0]>205)&(im[:,:,0]>im[:,:,1]*2)&(im[:,:,0]>im[:,:,2]*2)) if i==0 else ((im[:,:,1]>205)&(im[:,:,1]>im[:,:,0]*1.5)&(im[:,:,1]>im[:,:,2]*1.3)) + masks=[mask(im,i) for i in range(2)] + counts=[np.count_nonzero(masks[i])+np.count_nonzero(mask(tools.image('left_wrist' if i==0 else 'right_wrist'),i)) for i in range(2)] + for i in range(2): + if not self.lock[i] and counts[i]>=4: + dp,dy,el=self.offsets[self.index[i]%len(self.offsets)];p,y=self.guess[i] + self.poses[i]=np.array([p+dp-el,self.roll[i]*(1 if i==0 else -1),(y+dy)*(1 if i==0 else -1),el,0,0,0],dtype=np.float32) + self.lock[i]=True;self.locktime[i]=t + elif self.lock[i] and t-self.locktime[i]>40 and counts[i]<2 and not (all(self.lock) and t-max(self.locktime)<60): + self.lock[i]=False;self.index[i]+=1 + for i in range(2): + if self.lock[i]:q=self.poses[i] + else: + idx=self.index[i]%len(self.offsets);dp,dy,el=self.offsets[idx];p,y=self.guess[i];q=np.array([p+dp-el,self.roll[i]*(1 if i==0 else -1),(y+dy)*(1 if i==0 else -1),el,0,0,0]) + a[4+7*i:11+7*i]=q + if self.phase==2 and (t-self.phase_t)%21==20: + for i in range(2): + if not self.lock[i]:self.index[i]+=1 + return a diff --git a/policies/reach_target_dual/gpt61terra-s3/episodes.csv b/policies/reach_target_dual/gpt61terra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..e1b1cdcc40f105d6977aac51f530490873dabd7a --- /dev/null +++ b/policies/reach_target_dual/gpt61terra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,653,success,0 +620001,1,266,success,0 +620002,0,700,timeout,0 +620003,0,700,timeout,0 +620004,0,700,timeout,0 +620005,0,700,timeout,0 +620006,0,700,timeout,0 +620007,0,700,timeout,0 +620008,0,700,timeout,0 +620009,0,700,timeout,0 +620010,0,700,timeout,0 +620011,0,700,timeout,0 +620012,1,226,success,0 +620013,0,700,timeout,0 +620014,0,700,timeout,0 +620015,0,700,timeout,0 +620016,1,256,success,0 +620017,1,249,success,0 +620018,1,260,success,0 +620019,1,226,success,0 +620020,0,700,timeout,0 +620021,0,700,timeout,0 +620022,1,555,success,0 +620023,0,700,timeout,0 +620024,1,255,success,0 +620025,0,700,timeout,0 +620026,0,700,timeout,0 +620027,0,700,timeout,0 +620028,1,263,success,0 +620029,1,263,success,0 +620030,0,700,timeout,0 +620031,0,700,timeout,0 +620032,1,506,success,0 +620033,0,700,timeout,0 +620034,1,541,success,0 +620035,0,700,timeout,0 +620036,1,226,success,0 +620037,0,700,timeout,0 +620038,0,700,timeout,0 +620039,0,700,timeout,0 +620040,1,262,success,0 +620041,1,399,success,0 +620042,0,700,timeout,0 +620043,1,255,success,0 +620044,0,700,timeout,0 +620045,0,700,timeout,0 +620046,0,700,timeout,0 +620047,0,700,timeout,0 +620048,0,700,timeout,0 +620049,1,256,success,0 +620050,0,700,timeout,0 +620051,0,700,timeout,0 +620052,0,700,timeout,0 +620053,0,700,timeout,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,0,700,timeout,0 +620058,0,700,timeout,0 +620059,1,398,success,0 +620060,1,657,success,0 +620061,1,537,success,0 +620062,0,700,timeout,0 +620063,1,226,success,0 +620064,1,226,success,0 +620065,0,700,timeout,0 +620066,0,700,timeout,0 +620067,0,700,timeout,0 +620068,0,700,timeout,0 +620069,1,333,success,0 +620070,0,700,timeout,0 +620071,0,700,timeout,0 +620072,0,700,timeout,0 +620073,1,225,success,0 +620074,0,700,timeout,0 +620075,0,700,timeout,0 +620076,0,700,timeout,0 +620077,0,700,timeout,0 +620078,0,700,timeout,0 +620079,0,700,timeout,0 +620080,1,289,success,0 +620081,1,653,success,0 +620082,1,252,success,0 +620083,1,249,success,0 +620084,0,700,timeout,0 +620085,1,257,success,0 +620086,0,700,timeout,0 +620087,0,700,timeout,0 +620088,1,398,success,0 +620089,0,700,timeout,0 +620090,0,700,timeout,0 +620091,0,700,timeout,0 +620092,1,302,success,0 +620093,0,700,timeout,0 +620094,1,337,success,0 +620095,1,272,success,0 +620096,0,700,timeout,0 +620097,0,700,timeout,0 +620098,0,700,timeout,0 +620099,0,700,timeout,0 diff --git a/policies/reach_target_dual/gpt61terra-s3/policy.py b/policies/reach_target_dual/gpt61terra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d12dad1caf21532f3b52aebff796b6a95af9147f --- /dev/null +++ b/policies/reach_target_dual/gpt61terra-s3/policy.py @@ -0,0 +1,63 @@ +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[18:20]=0 + self.start=float(obs['low_dim_obs'][18]); self.lock=[None,None]; self.locktime=[0,0]; self.prev=-1; self.last=[None,None]; self.dark=[0,0]; self.retries=[0,0] + im=tools.image('head').astype(np.int16); R,G,B=im[:,:,0],im[:,:,1],im[:,:,2] + masks=[(R>50)&(R>G*1.55)&(R>B*1.4),(G>45)&(G>R*1.5)&(G>B*1.2)] + self.initial=[]; self.missing=any(np.count_nonzero(m)<6 for m in masks) + for side,m in enumerate(masks): + y,x=np.where(m) + if len(x)>5: + xc=float(np.mean(x)); yc=float(np.mean(y)) + if x.min()==0: xc-=3 + if x.max()==83: xc+=3 + if y.min()==0: yc-=3 + else: xc=0 if side==0 else 84; yc=12 + roll=np.clip((42-xc)*.0075 + (0.10 if xc<8 else (-0.10 if xc>76 else 0)), -.52,.52) + pitch=np.clip(-1.4+.04*yc,-1.35,-.53) + self.initial.append([pitch,roll]) + self.cmd=[None,None] + def act(self,obs,tools): + t=obs['t']; a=self.a.copy(); p=obs['low_dim_obs']; dx=self.start+.105-float(p[18]) + if t<120 and dx>.014: a[0]=.16 + else: a[0]=0 + if t%5==0 and t>30: + im=tools.image('head').astype(np.int16); R,G,B=im[:,:,0],im[:,:,1],im[:,:,2] + bright=[int(np.sum((R>190)&(R>G*1.7)&(R>B*1.5))),int(np.sum((G>190)&(G>R*1.7)&(G>B*1.3)))] + for side, camera in enumerate(('left_wrist','right_wrist')): + w=tools.image(camera).astype(np.int16); r,g,b=w[:,:,0],w[:,:,1],w[:,:,2] + if side==0: bright[side]+=int(np.sum((r>190)&(r>g*1.7)&(r>b*1.5))) + else: bright[side]+=int(np.sum((g>190)&(g>r*1.7)&(g>b*1.3))) + for side in range(2): + if bright[side]>5 and self.lock[side] is None and a[0]==0: + cur=p[0:7] if side==0 else p[9:16] + v=cur.copy(); v[0]-=.04;v[3]-=.025;v[5]=0 + self.lock[side]=v; self.last[side]=v.copy(); self.locktime[side]=t; self.dark[side]=0 + elif self.lock[side] is not None: + if bright[side]>3: self.dark[side]=0 + else: self.dark[side]+=5 + if self.dark[side]>=25: + self.lock[side]=None; self.retries[side]+=1; self.dark[side]=0 + phase=max(0,(t-100)//35) + # Small deterministic variations cover vertical and lateral uncertainty. + offsets=[(0,0,0),(-.18,0,0),(.18,0,0),(0,0,.22),(0,-.10,0),(0,.10,0),(0,0,-.22),(-.18,0,.20),(.18,0,-.20),(-.18,.10,0),(.18,-.10,0),(0,.1,.2),(0,-.1,-.2),(-.3,0,0),(.3,0,0),(0,.15,0),(0,-.15,0)] + if self.missing: + phase=max(0,(t-100)//40) + offsets=[(0,0,0),(-.18,0,0),(.18,0,0),(0,.09,0),(0,-.09,0),(-.15,.06,.12),(.15,-.06,-.12),(-.3,0,.08),(.3,0,-.08),(0,.14,.1),(0,-.14,-.1)] + dp,dr,de=offsets[phase%len(offsets)] + for s in range(2): + if self.lock[s] is not None: v=self.lock[s] + else: + base,roll=self.initial[s]; pitch=np.clip(base+dp,-1.6,-.4) + v=[pitch,np.clip(roll+dr*(1 if s==0 else -1),-.55,.55),0,-pitch+.14+de,0,0,0] + if self.last[s] is not None: + v=self.last[s].copy() + q=(self.retries[s]-1)%8 + v[0]+=[.04,-.04,0,0,0,0,.06,-.06][q] + v[1]+=[0,0,.04,-.04,0,0,.02,-.02][q] + v[3]+=[0,0,0,0,.06,-.06,-.04,.04][q] + a[4+7*s:11+7*s]=v + return a diff --git a/policies/reach_target_dual/gpt6sol-s1/episodes.csv b/policies/reach_target_dual/gpt6sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..2816f8e6315d0b411dd6330c224691130dcf5799 --- /dev/null +++ b/policies/reach_target_dual/gpt6sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,700,timeout,0 +620001,1,460,success,0 +620002,0,700,timeout,0 +620003,0,700,timeout,0 +620004,1,651,success,0 +620005,0,700,timeout,0 +620006,0,700,timeout,0 +620007,0,700,timeout,0 +620008,0,700,timeout,0 +620009,0,700,timeout,0 +620010,0,700,timeout,0 +620011,1,173,success,0 +620012,1,321,success,0 +620013,0,700,timeout,0 +620014,0,700,timeout,0 +620015,0,700,timeout,0 +620016,0,700,timeout,0 +620017,0,700,timeout,0 +620018,1,343,success,0 +620019,0,700,timeout,0 +620020,1,303,success,0 +620021,0,700,timeout,0 +620022,0,700,timeout,0 +620023,0,700,timeout,0 +620024,1,494,success,0 +620025,0,700,timeout,0 +620026,0,700,timeout,0 +620027,0,700,timeout,0 +620028,0,700,timeout,0 +620029,0,700,timeout,0 +620030,0,700,timeout,0 +620031,0,700,timeout,0 +620032,1,193,success,0 +620033,0,700,timeout,0 +620034,1,322,success,0 +620035,1,500,success,0 +620036,1,581,success,0 +620037,1,194,success,0 +620038,0,700,timeout,0 +620039,0,700,timeout,0 +620040,1,305,success,0 +620041,0,700,timeout,0 +620042,0,700,timeout,0 +620043,0,700,timeout,0 +620044,0,700,timeout,0 +620045,0,700,timeout,0 +620046,0,700,timeout,0 +620047,1,645,success,0 +620048,0,700,timeout,0 +620049,1,299,success,0 +620050,0,700,timeout,0 +620051,0,700,timeout,0 +620052,0,700,timeout,0 +620053,0,700,timeout,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,0,700,timeout,0 +620058,1,479,success,0 +620059,1,665,success,0 +620060,1,304,success,0 +620061,0,700,timeout,0 +620062,0,700,timeout,0 +620063,1,171,success,0 +620064,1,320,success,0 +620065,0,700,timeout,0 +620066,0,700,timeout,0 +620067,0,700,timeout,0 +620068,1,166,success,0 +620069,0,700,timeout,0 +620070,0,700,timeout,0 +620071,0,700,timeout,0 +620072,0,700,timeout,0 +620073,1,259,success,0 +620074,1,318,success,0 +620075,0,700,timeout,0 +620076,0,700,timeout,0 +620077,1,330,success,0 +620078,0,700,timeout,0 +620079,0,700,timeout,0 +620080,1,337,success,0 +620081,0,700,timeout,0 +620082,1,260,success,0 +620083,1,332,success,0 +620084,0,700,timeout,0 +620085,0,700,timeout,0 +620086,0,700,timeout,0 +620087,0,700,timeout,0 +620088,0,700,timeout,0 +620089,0,700,timeout,0 +620090,1,171,success,0 +620091,0,700,timeout,0 +620092,1,284,success,0 +620093,0,700,timeout,0 +620094,1,389,success,0 +620095,1,468,success,0 +620096,1,303,success,0 +620097,0,700,timeout,0 +620098,0,700,timeout,0 +620099,1,312,success,0 diff --git a/policies/reach_target_dual/gpt6sol-s1/policy.py b/policies/reach_target_dual/gpt6sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..59a67c9ba6f2255371f136ae29d61ec58cc230b4 --- /dev/null +++ b/policies/reach_target_dual/gpt6sol-s1/policy.py @@ -0,0 +1,125 @@ +"""Deterministic image based reaching controller.""" + +import cv2 +import numpy as np + + +def _sphere_data(rgb): + hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV) + h, s, v = cv2.split(hsv) + masks = [(((h <= 13) | (h >= 171)) & (s > 80) & (v > 30)), + (((h >= 34) & (h <= 91)) & (s > 70) & (v > 30))] + out = [] + for mask in masks: + n, labels, stats, centers = cv2.connectedComponentsWithStats(mask.astype(np.uint8)) + if n <= 1: + out.append((None, 0.0)) + continue + j = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + area = stats[j, cv2.CC_STAT_AREA] + if area < 7: + out.append((None, 0.0)) + else: + values = v[labels == j] + out.append((centers[j].copy(), float(np.mean(values)))) + return out + + +class Policy: + def reset(self, obs, tools): + requested_steps = getattr(self, "approach_steps", None) + self.action = np.asarray(tools.hold_action(), dtype=np.float32) + self.action[:] = 0 + self.action[2] = .74 + self.action[4] = self.action[11] = -.8 + self.action[7] = self.action[14] = 1.0 + self.action[13] = -.6 + self.initial = _sphere_data(tools.image("head")) + self.centers = [x[0] for x in self.initial] + if requested_steps is None and all(c is not None for c in self.centers): + avg_y = .5 * (self.centers[0][1] + self.centers[1][1]) + self.approach_steps = int(np.clip(round(110. - 3. * avg_y), 35, 110)) + else: + self.approach_steps = 65 if requested_steps is None else requested_steps + self.candidates = [self._candidates(i) for i in range(2)] + self.width = (self.centers[1][0] - self.centers[0][0] + if all(c is not None for c in self.centers) else 0.) + self.search_origin = self.approach_steps + self.fallback = False + self.ever_bright = [False, False] + self.index = [0, 0] + self.locked = [False, False] + self.bright_streak = [0, 0] + self.dark_streak = [0, 0] + self.lock_target = [None, None] + + def _candidates(self, side): + center = self.centers[side] + if side == 0: + x, y = (25., 15.) if center is None else center + nominal = np.array([-.8 + .010 * (y - 15.), + np.clip((25. - x) / 90., -.05, .35), + 0., 1.], dtype=float) + else: + x, y = (72., 18.) if center is None else center + nominal = np.array([-.8 + .008 * (y - 18.), 0., + np.clip(-.6 + (74. - x) / 30., -1.1, .2), 1.], dtype=float) + # shoulder pitch, roll, yaw, elbow offsets + offsets = [ + (0, 0, 0, 0), (0, 0, 0, .1), (0, 0, 0, -.1), + (.1, 0, 0, 0), (-.1, 0, 0, 0), + (0, 0, .15, 0), (0, 0, -.15, 0), + (0, .1, 0, 0), (0, -.1, 0, 0), + (.1, 0, 0, .1), (-.1, 0, 0, .1), + (.1, 0, .15, 0), (.1, 0, -.15, 0), + (-.1, 0, .15, 0), (-.1, 0, -.15, 0), + (0, .2, 0, 0), (0, -.2, 0, 0), + (.2, 0, 0, 0), (-.2, 0, 0, 0), + (0, 0, .3, 0), (0, 0, -.3, 0), + (0, 0, 0, .2), (0, 0, 0, -.2), + ] + if side == 0 and x < 10.: + offsets.insert(0, (0, 0, .3, 0)) + return [np.clip(nominal + off, + [-1.5, -.05 if side == 0 else -.7, -1.7, .5], + [.2, .7 if side == 0 else .06, 1.2, 1.5]) + for off in offsets] + + def act(self, obs, tools): + t = int(obs["t"]) + a = self.action + a[0] = .1 if t < self.approach_steps else 0. + if t < self.approach_steps: + return a.copy() + if t == 300 and self.width > 57. and not all(self.ever_bright): + self.fallback = True + if self.fallback and 300 <= t < 336: + a[0] = .1 + if self.fallback and t == 336: + self.search_origin = 336 + self.index = [0, 0] + data = _sphere_data(tools.image("head")) + q = obs["low_dim_obs"] + for side in (0, 1): + center, value = data[side] + is_bright = center is not None and value > 175. + if is_bright: + self.ever_bright[side] = True + self.bright_streak[side] = self.bright_streak[side] + 1 if is_bright else 0 + self.dark_streak[side] = 0 if is_bright else self.dark_streak[side] + 1 + if self.locked[side] and self.dark_streak[side] > 10: + self.locked[side] = False + self.index[side] += 1 + if not self.locked[side] and self.bright_streak[side] >= 3: + self.locked[side] = True + start = 0 if side == 0 else 9 + self.lock_target[side] = np.array([q[start], q[start+1], q[start+2], q[start+3]]) + slot = 4 if side == 0 else 11 + if self.locked[side]: + target = self.lock_target[side] + else: + stage = (t - self.search_origin) // 24 + self.index[side] = max(self.index[side], stage) + target = self.candidates[side][self.index[side] % len(self.candidates[side])] + a[slot:slot+4] = target + return a.copy() diff --git a/policies/reach_target_dual/gpt6sol-s2/episodes.csv b/policies/reach_target_dual/gpt6sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..9fbdd828f43a2e43e33fe6d2daf34588f0db3b7a --- /dev/null +++ b/policies/reach_target_dual/gpt6sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,501,success,0 +620001,1,220,success,0 +620002,0,700,timeout,0 +620003,1,248,success,0 +620004,1,224,success,0 +620005,0,700,timeout,0 +620006,0,700,timeout,0 +620007,0,700,timeout,0 +620008,1,166,success,0 +620009,0,700,timeout,0 +620010,1,167,success,0 +620011,1,168,success,0 +620012,1,286,success,0 +620013,0,700,timeout,0 +620014,0,700,timeout,0 +620015,0,700,timeout,0 +620016,0,700,timeout,0 +620017,0,700,timeout,0 +620018,0,700,timeout,0 +620019,1,198,success,0 +620020,1,199,success,0 +620021,1,433,success,0 +620022,0,700,timeout,0 +620023,0,700,timeout,0 +620024,1,246,success,0 +620025,0,700,timeout,0 +620026,1,184,success,0 +620027,0,700,timeout,0 +620028,1,286,success,0 +620029,1,203,success,0 +620030,0,700,timeout,0 +620031,0,700,timeout,0 +620032,1,343,success,0 +620033,1,274,success,0 +620034,0,700,timeout,0 +620035,1,411,success,0 +620036,1,187,success,0 +620037,0,700,timeout,0 +620038,0,700,timeout,0 +620039,1,256,success,0 +620040,1,172,success,0 +620041,1,200,success,0 +620042,1,221,success,0 +620043,1,363,success,0 +620044,1,363,success,0 +620045,0,700,timeout,0 +620046,1,168,success,0 +620047,1,602,success,0 +620048,1,202,success,0 +620049,1,188,success,0 +620050,1,196,success,0 +620051,0,700,timeout,0 +620052,1,208,success,0 +620053,0,700,timeout,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,1,174,success,0 +620057,1,213,success,0 +620058,1,242,success,0 +620059,1,588,success,0 +620060,1,243,success,0 +620061,1,299,success,0 +620062,0,700,timeout,0 +620063,1,180,success,0 +620064,1,200,success,0 +620065,0,700,timeout,0 +620066,0,700,timeout,0 +620067,0,700,timeout,0 +620068,1,259,success,0 +620069,0,700,timeout,0 +620070,0,700,timeout,0 +620071,1,206,success,0 +620072,0,700,timeout,0 +620073,1,179,success,0 +620074,1,232,success,0 +620075,0,700,timeout,0 +620076,1,221,success,0 +620077,1,243,success,0 +620078,1,411,success,0 +620079,0,700,timeout,0 +620080,1,381,success,0 +620081,1,185,success,0 +620082,1,419,success,0 +620083,1,173,success,0 +620084,0,700,timeout,0 +620085,0,700,timeout,0 +620086,0,700,timeout,0 +620087,0,700,timeout,0 +620088,0,700,timeout,0 +620089,1,326,success,0 +620090,1,234,success,0 +620091,0,700,timeout,0 +620092,1,409,success,0 +620093,0,700,timeout,0 +620094,1,269,success,0 +620095,1,407,success,0 +620096,0,700,timeout,0 +620097,1,380,success,0 +620098,1,338,success,0 +620099,1,392,success,0 diff --git a/policies/reach_target_dual/gpt6sol-s2/policy.py b/policies/reach_target_dual/gpt6sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..474f00ae3af4285c7bdde27a2a08dfa4d22617bc --- /dev/null +++ b/policies/reach_target_dual/gpt6sol-s2/policy.py @@ -0,0 +1,119 @@ +"""Deterministic visual feedback controller for the two target spheres.""" + +import numpy as np +import cv2 + + +def contact_pixels(image): + rgb = image.astype(np.int16) + r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] + red = (r > 205) & (r > 1.65 * g) & (r > 1.5 * b) + green = (g > 205) & (g > 1.4 * r) & (g > 1.25 * b) + return int(red.sum()), int(green.sum()) + + +def target_center(image, color): + hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) + if color == 'red': + mask = cv2.inRange(hsv, (0, 85, 45), (12, 255, 255)) + mask |= cv2.inRange(hsv, (170, 85, 45), (179, 255, 255)) + else: + mask = cv2.inRange(hsv, (36, 55, 35), (90, 255, 255)) + n, labels, stats, centers = cv2.connectedComponentsWithStats(mask) + if n < 2: + return None + idx = 1 + np.argmax(stats[1:, 4]) + if stats[idx, 4] < 25: + return None + return centers[idx] + + +class Policy: + def reset(self, obs, tools): + self.start_x = float(obs['low_dim_obs'][18]) + green_start = target_center(tools.image('head'), 'green') + self.low_green = bool(green_start is not None and green_start[1] > 22) + self.right_seen = False + self.arm = [[-0.35, 0.35], [-0.5, -0.35]] + self.triggered = False + self.trigger_x = None + self.first_contact_x = None + self.ever_bright = [False, False] + self.contact_y = 0.0 + self.contact_yaw = 0.0 + self.candidates = [] + for roll in (0.0, 0.1, -0.1, 0.2, -0.2, 0.3, -0.3): + for pitch in (0.0, -0.1, 0.1, -0.2, 0.2, -0.3, 0.3): + self.candidates.append((pitch, roll)) + self.idx = [0, 0] + self.missing = [0, 0] + self.step_in_candidate = [0, 0] + + def act(self, obs, tools): + t = int(obs['t']) + x = float(obs['low_dim_obs'][18]) + y = float(obs['low_dim_obs'][19]) + yaw = float(obs['low_dim_obs'][21]) + delta = max(0.0, x - self.start_x) + head = tools.image('head') + nr, ng = contact_pixels(head) + if nr < 6: + nr = max(nr, contact_pixels(tools.image('left_wrist'))[0]) + if ng < 6: + ng = max(ng, contact_pixels(tools.image('right_wrist'))[1]) + bright = [nr >= 6, ng >= 6] + if t >= 60: + self.ever_bright[0] |= bright[0] + self.ever_bright[1] |= bright[1] + action = np.asarray(tools.hold_action(), dtype=np.float32) + action[18:20] = 0.0 + if t in (20, 30, 40, 50): + for side, camera, color in ((0, 'left_wrist', 'red'), (1, 'right_wrist', 'green')): + center = target_center(tools.image(camera), color) + if center is not None: + if side == 1: + self.right_seen = True + cx, cy = center + self.arm[side][0] += np.clip(0.8 * (cy - 30.0) / 180.0, -0.22, 0.22) + self.arm[side][1] += np.clip(0.8 * (40.0 - cx) / 145.0, -0.25, 0.25) + self.arm[side][0] = float(np.clip(self.arm[side][0], -0.9, 0.35)) + self.arm[side][1] = float(np.clip(self.arm[side][1], -0.8, 0.8)) + if t == 60 and self.low_green and not self.right_seen: + self.arm[1][0] = -0.15 + if not self.triggered: + if t >= 60 and self.ever_bright[0] and self.ever_bright[1] and self.first_contact_x is None: + self.first_contact_x = x + action[0] = 0.12 if t >= 60 and delta < 0.28 else 0.0 + if t > 60 and (self.first_contact_x is not None or delta >= 0.25): + self.triggered = True + self.trigger_x = x + 0.02 + self.contact_y = y + self.contact_yaw = yaw + action[0] = 0.0 + else: + error_x = self.trigger_x - x + action[0] = np.sign(error_x) * 0.08 if abs(error_x) > 0.012 else 0.0 + for side in (0, 1): + if bright[side]: + self.missing[side] = 0 + self.step_in_candidate[side] = 0 + else: + self.missing[side] += 1 + if self.missing[side] >= 9: + self.step_in_candidate[side] += 1 + if self.step_in_candidate[side] >= 18: + self.idx[side] = (self.idx[side] + 1) % len(self.candidates) + self.step_in_candidate[side] = 0 + base_left = self.arm[0][0] + 1.5 * delta + base_right = self.arm[1][0] + 1.5 * delta + if self.triggered: + left_pitch, left_roll = self.candidates[self.idx[0]] + right_pitch, right_roll = self.candidates[self.idx[1]] + body_roll_correction = float(np.clip(2.5 * (self.contact_y - y) + 0.5 * (self.contact_yaw - yaw), -0.15, 0.15)) + left_roll += body_roll_correction + right_roll += body_roll_correction + else: + left_pitch = left_roll = right_pitch = right_roll = 0.0 + action[4:11] = [base_left + left_pitch, self.arm[0][1] + left_roll, 0, 0.25, 0, 0, 0] + action[11:18] = [base_right + right_pitch, self.arm[1][1] + right_roll, 0, 0.25, 0, 0, 0] + return action diff --git a/policies/reach_target_dual/gpt6sol-s3/episodes.csv b/policies/reach_target_dual/gpt6sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..d712e2dd3297d35dfa6de0589b3f20b35493aadf --- /dev/null +++ b/policies/reach_target_dual/gpt6sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,700,timeout,0 +620001,0,700,timeout,0 +620002,0,700,timeout,0 +620003,1,191,success,0 +620004,1,90,success,0 +620005,0,700,timeout,0 +620006,0,700,timeout,0 +620007,1,217,success,0 +620008,0,700,timeout,0 +620009,0,700,timeout,0 +620010,0,700,timeout,0 +620011,1,238,success,0 +620012,1,165,success,0 +620013,0,700,timeout,0 +620014,0,700,timeout,0 +620015,0,700,timeout,0 +620016,0,700,timeout,0 +620017,0,700,timeout,0 +620018,0,700,timeout,0 +620019,0,700,timeout,0 +620020,1,254,success,0 +620021,1,86,success,0 +620022,0,700,timeout,0 +620023,0,700,timeout,0 +620024,0,700,timeout,0 +620025,0,700,timeout,0 +620026,0,700,timeout,0 +620027,0,700,timeout,0 +620028,0,700,timeout,0 +620029,1,193,success,0 +620030,0,700,timeout,0 +620031,0,700,timeout,0 +620032,0,700,timeout,0 +620033,0,700,timeout,0 +620034,0,700,timeout,0 +620035,0,700,timeout,0 +620036,0,700,timeout,0 +620037,0,700,timeout,0 +620038,0,700,timeout,0 +620039,0,700,timeout,0 +620040,0,700,timeout,0 +620041,1,207,success,0 +620042,0,700,timeout,0 +620043,0,700,timeout,0 +620044,0,700,timeout,0 +620045,0,700,timeout,0 +620046,0,700,timeout,0 +620047,0,700,timeout,0 +620048,1,170,success,0 +620049,0,700,timeout,0 +620050,0,700,timeout,0 +620051,0,700,timeout,0 +620052,0,700,timeout,0 +620053,0,700,timeout,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,0,700,timeout,0 +620058,1,171,success,0 +620059,0,700,timeout,0 +620060,1,187,success,0 +620061,0,700,timeout,0 +620062,0,700,timeout,0 +620063,0,700,timeout,0 +620064,0,700,timeout,0 +620065,0,700,timeout,0 +620066,1,348,success,0 +620067,0,700,timeout,0 +620068,0,700,timeout,0 +620069,0,700,timeout,0 +620070,0,700,timeout,0 +620071,0,700,timeout,0 +620072,0,700,timeout,0 +620073,1,117,success,0 +620074,0,700,timeout,0 +620075,0,700,timeout,0 +620076,0,700,timeout,0 +620077,0,700,timeout,0 +620078,0,700,timeout,0 +620079,0,700,timeout,0 +620080,0,700,timeout,0 +620081,1,247,success,0 +620082,1,185,success,0 +620083,1,237,success,0 +620084,0,700,timeout,0 +620085,0,700,timeout,0 +620086,0,700,timeout,0 +620087,0,700,timeout,0 +620088,0,700,timeout,0 +620089,0,700,timeout,0 +620090,0,700,timeout,0 +620091,0,700,timeout,0 +620092,0,700,timeout,0 +620093,0,700,timeout,0 +620094,0,700,timeout,0 +620095,0,700,timeout,0 +620096,1,210,success,0 +620097,0,700,timeout,0 +620098,1,275,success,0 +620099,1,448,success,0 diff --git a/policies/reach_target_dual/gpt6sol-s3/policy.py b/policies/reach_target_dual/gpt6sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..109f79ff3015e18ea11dcd7f32a999d3d719c98f --- /dev/null +++ b/policies/reach_target_dual/gpt6sol-s3/policy.py @@ -0,0 +1,97 @@ +"""Hand-written reaching controller for the dual-sphere task.""" + +import numpy as np + + +class Policy: + @staticmethod + def target(im, side): + r, g, b = (im[:, :, k].astype(np.int16) for k in range(3)) + if side == 'red': + mask = (r > 1.5 * g) & (r > 1.3 * b) & (r > 45) + else: + mask = (g > 1.3 * r) & (g > 1.1 * b) & (g > 35) + ys, xs = np.where(mask) + if len(xs) < 5: + return (5.0, 12.0) if side == 'red' else (77.0, 2.0) + return float(xs.mean()), float(ys.mean()) + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + im = tools.image('head') + rx, ry = self.target(im, 'red') + gx, gy = self.target(im, 'green') + self.lp = np.clip((ry - 12) * .02, -.5, .5) + self.lq = np.clip(.15 + (5 - rx) * .0075, -.3, .45) + self.rp = np.clip(-.3 + (gy - 2) * .025, -.6, .4) + self.rr = np.clip(-(gy - 2) * .0125, -.35, .1) + self.rq = np.clip(.25 + (gx - 77) * .06, -.1, .6) + self.ty = max(0.0, (40.0 - (rx + gx) * .5) * .005) + self.fast = gy < 8 + self.stop_t = None + self.recover_side = None + self.recover_start = None + self.last_both_t = -1000 + self.saved_pose = None + self.last_action = self.hold.copy() + self.switched_recovery = False + + @staticmethod + def touched(im): + r, g, b = (im[:, :, k].astype(np.int16) for k in range(3)) + red = (r > 1.5 * g) & (r > 1.3 * b) & (r > 45) + green = (g > 1.3 * r) & (g > 1.1 * b) & (g > 35) + return (bool(np.any(r[red] >= 240)), + bool(np.any(g[green] >= 240))) + + def act(self, obs, tools): + t = int(obs['t']) + a = self.hold.copy() + hit = (False, False) + if not self.fast and self.stop_t is None and t < 110: + hit = self.touched(tools.image('head')) + if all(hit): + self.stop_t = t + if self.fast: + moving = t < 30 + a[0] = .3 if moving else 0.0 + else: + moving = (self.stop_t is None and t < 110) or (self.stop_t is not None and t < self.stop_t) + a[0] = .15 if moving else 0.0 + if moving: + y = float(obs['low_dim_obs'][19]) + a[1] = np.clip(self.ty - y, -.08, .08) + a[2] = .74 + a[4:11] = [self.lp, 0, self.lq, 0, 0, 0, 0] + a[11:18] = [self.rp, self.rr, -self.rq, 0, 0, 0, 0] + if t >= (120 if self.fast else max(160, (self.stop_t or 110) + 60)): + hit = self.touched(tools.image('head')) + if self.recover_start is None: + self.recover_start = t + self.recover_side = 'left' if hit[1] and not hit[0] else 'right' + if t >= 300 and not self.switched_recovery: + new_side = 'left' if hit[1] and not hit[0] else 'right' if hit[0] and not hit[1] else self.recover_side + if new_side != self.recover_side: + self.recover_side = new_side + self.recover_start = t + self.switched_recovery = True + if all(hit): + self.last_both_t = t + self.saved_pose = self.last_action[4:18].copy() if self.saved_pose is None else self.saved_pose + if self.saved_pose is not None and t - self.last_both_t < 60: + a[4:18] = self.saved_pose + else: + self.saved_pose = None + offsets = [(.0,.15,0),(.0,-.15,0),(.0,.3,0),(.0,-.3,0),(.15,0,0),(-.15,0,0),(.15,.15,0),(-.15,-.15,0),(.15,-.15,0),(-.15,.15,0),(.0,.45,0),(.0,-.45,0),(-.1,.15,-.1),(.1,.15,-.1),(0,.15,.1),(0,-.15,-.1),(0,.3,-.1),(0,-.3,.1),(-.2,0,-.2),(.2,0,.1)] + idx = min((t - self.recover_start) // 25, len(offsets) - 1) + dp,dq,dr = offsets[idx] + if self.recover_side == 'left': + a[4] = np.clip(self.lp + dp, -1.0, 1.0) + a[5] = np.clip(dr, -.4, .4) + a[6] = np.clip(self.lq + dq, -1.0, 1.0) + else: + a[11] = np.clip(self.rp + dp, -1.0, 1.0) + a[12] = np.clip(self.rr + dr, -.7, .3) + a[13] = np.clip(-(self.rq + dq), -1.0, 1.0) + self.last_action = a.copy() + return a diff --git a/policies/reach_target_dual/kimi31pro-s1/episodes.csv b/policies/reach_target_dual/kimi31pro-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..d4259e14792ad4d9aececc823bab7ba61bf11e96 --- /dev/null +++ b/policies/reach_target_dual/kimi31pro-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,700,timeout,0 +620001,0,700,timeout,0 +620002,0,700,timeout,0 +620003,0,700,timeout,0 +620004,0,700,timeout,0 +620005,0,700,timeout,0 +620006,0,700,timeout,0 +620007,0,700,timeout,0 +620008,0,700,timeout,0 +620009,0,700,timeout,0 +620010,0,700,timeout,0 +620011,0,700,timeout,0 +620012,0,700,timeout,0 +620013,0,700,timeout,0 +620014,0,700,timeout,0 +620015,0,700,timeout,0 +620016,0,700,timeout,0 +620017,0,700,timeout,0 +620018,0,700,timeout,0 +620019,0,700,timeout,0 +620020,0,700,timeout,0 +620021,0,700,timeout,0 +620022,0,700,timeout,0 +620023,0,700,timeout,0 +620024,0,700,timeout,0 +620025,0,700,timeout,0 +620026,0,700,timeout,0 +620027,0,700,timeout,0 +620028,0,700,timeout,0 +620029,0,700,timeout,0 +620030,0,700,timeout,0 +620031,0,700,timeout,0 +620032,0,700,timeout,0 +620033,0,700,timeout,0 +620034,0,700,timeout,0 +620035,0,700,timeout,0 +620036,0,700,timeout,0 +620037,0,700,timeout,0 +620038,0,700,timeout,0 +620039,0,700,timeout,0 +620040,0,700,timeout,0 +620041,0,700,timeout,0 +620042,0,700,timeout,0 +620043,0,700,timeout,0 +620044,0,700,timeout,0 +620045,0,700,timeout,0 +620046,0,700,timeout,0 +620047,0,700,timeout,0 +620048,0,700,timeout,0 +620049,0,700,timeout,0 +620050,0,700,timeout,0 +620051,0,700,timeout,0 +620052,0,700,timeout,0 +620053,0,700,timeout,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,0,700,timeout,0 +620058,0,700,timeout,0 +620059,0,700,timeout,0 +620060,0,700,timeout,0 +620061,0,700,timeout,0 +620062,0,700,timeout,0 +620063,0,700,timeout,0 +620064,0,700,timeout,0 +620065,0,700,timeout,0 +620066,0,700,timeout,0 +620067,0,700,timeout,0 +620068,0,700,timeout,0 +620069,0,700,timeout,0 +620070,0,700,timeout,0 +620071,0,700,timeout,0 +620072,0,700,timeout,0 +620073,0,700,timeout,0 +620074,0,700,timeout,0 +620075,0,700,timeout,0 +620076,0,700,timeout,0 +620077,0,700,timeout,0 +620078,0,700,timeout,0 +620079,0,700,timeout,0 +620080,0,700,timeout,0 +620081,0,700,timeout,0 +620082,0,700,timeout,0 +620083,0,700,timeout,0 +620084,0,700,timeout,0 +620085,0,700,timeout,0 +620086,0,700,timeout,0 +620087,0,700,timeout,0 +620088,0,700,timeout,0 +620089,0,700,timeout,0 +620090,0,700,timeout,0 +620091,0,700,timeout,0 +620092,0,700,timeout,0 +620093,0,700,timeout,0 +620094,0,700,timeout,0 +620095,0,700,timeout,0 +620096,0,700,timeout,0 +620097,0,700,timeout,0 +620098,0,700,timeout,0 +620099,0,700,timeout,0 diff --git a/policies/reach_target_dual/kimi31pro-s1/policy.py b/policies/reach_target_dual/kimi31pro-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..32db3d5680ec43f4a375c2a949449f891dccf071 --- /dev/null +++ b/policies/reach_target_dual/kimi31pro-s1/policy.py @@ -0,0 +1,176 @@ +"""Deterministic visual reaching policy for the Unitree G1. + +The controller uses only proprioception and the three onboard cameras. It is a +hand-written collection of reaching primitives with wrist-camera visual servoing +where useful; it has no learned models or runtime demonstration dependency. +""" + +import numpy as np + + +MIRROR = np.array([1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0], dtype=np.float32) + + +def _blob(image, color): + """Return a colored sphere's centroid and a conservative radius estimate.""" + a = np.asarray(image, dtype=np.int16) + if color == "red": + mask = ( + (a[:, :, 0] > 1.4 * a[:, :, 1]) + & (a[:, :, 0] > 1.4 * a[:, :, 2]) + & (a[:, :, 0] > 35) + ) + else: + mask = ( + (a[:, :, 1] > 1.2 * a[:, :, 0]) + & (a[:, :, 1] > 1.15 * a[:, :, 2]) + & (a[:, :, 1] > 25) + ) + ys, xs = np.nonzero(mask) + if len(xs) < 8: + return None + # The largest image extent is less sensitive to mild edge clipping than area. + radius = 0.5 * max(xs.max() - xs.min() + 1, ys.max() - ys.min() + 1) + return np.array([xs.mean(), ys.mean()], dtype=np.float32), float(radius) + + +class Policy: + 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.x0 = float(state[18]) + self.left = state[0:7].copy() + self.right = state[9:16].copy() + self.previous_left = self.left.copy() + self.previous_right = self.right.copy() + self.stage = -1 + self.t = 0 + + red = _blob(tools.image("head"), "red") + green = _blob(tools.image("head"), "green") + # Reference image measurements from the demonstration's initial layout. + # Deviations only apply small, bounded corrections to the primitives. + if red is None: + red_xy, red_radius = np.array([4.55, 11.87], dtype=np.float32), 7.0 + else: + red_xy, red_radius = red + if green is None: + green_xy, green_radius = np.array([77.13, 2.21], dtype=np.float32), 7.0 + else: + green_xy, green_radius = green + + self.pitch_left = float(np.clip(0.008 * (red_xy[1] - 11.87), -0.25, 0.25)) + self.pitch_right = float(np.clip(0.008 * (green_xy[1] - 2.21), -0.25, 0.25)) + self.roll_left = float(np.clip(-0.012 * (red_xy[0] - 4.55), -0.25, 0.25)) + self.roll_right = float(np.clip(0.012 * (green_xy[0] - 77.13), -0.25, 0.25)) + mean_radius = 0.5 * (red_radius + green_radius) + self.depth_correction = float(np.clip(0.015 * (7.0 - mean_radius), -0.06, 0.12)) + + # (base advance, left arm, right arm, use wrist contact servo, duration) + self.primitives = [ + ( + 0.18, + np.array([-0.8, 0.24, 0.0, 1.4, 0, 0, 0], dtype=np.float32), + np.array([-0.8, -0.26, 0.0, 1.4, 0, 0, 0], dtype=np.float32), + False, + 130, + ), + ( + 0.0, + np.array([-1.4, 0.2, 0.0, 1.6, 0, 0, 0], dtype=np.float32), + np.array([-1.4, -0.2, 0.0, 1.6, 0, 0, 0], dtype=np.float32), + True, + 130, + ), + ( + 0.18, + np.array([-1.1803, 0.0225, 0.5206, 1.0898, 0, 0, 0], dtype=np.float32), + np.array([-1.4699, -0.2743, 0.0568, 0.6720, 0, 0, 0], dtype=np.float32), + False, + 130, + ), + ( + 0.0, + np.array([-1.05, 0.4, 0.0, 1.1, 0, 0, 0], dtype=np.float32), + np.array([-1.05, -0.4, 0.0, 1.1, 0, 0, 0], dtype=np.float32), + True, + 130, + ), + ( + 0.35, + np.array([-0.8, 0.2, 0.0, 1.4, 0, 0, 0], dtype=np.float32), + np.array([-0.8, -0.2, 0.0, 1.4, 0, 0, 0], dtype=np.float32), + False, + 180, + ), + ] + + def _corrected(self, arm, left): + q = np.asarray(arm, dtype=np.float32).copy() + if left: + q[0] += self.pitch_left + q[1] += self.roll_left + q[1] = np.clip(q[1], -1.45, 1.45) + else: + q[0] += self.pitch_right + q[1] -= self.roll_right + q[1] = np.clip(q[1], -1.45, 1.45) + q[0] = np.clip(q[0], -2.8, 2.5) + q[2] = np.clip(q[2], -2.5, 2.5) + q[3] = np.clip(q[3], -1.0, 2.05) + return q + + def _servo(self, image, q, left): + found = _blob(image, "red" if left else "green") + if found is None: + return + (x, y), _ = found + tx, ty = (34.0, 42.0) if left else (46.0, 55.0) + q[5] += np.clip(0.004 * (y - ty), -0.025, 0.025) + q[6] += np.clip(0.004 * (tx - x), -0.025, 0.025) + q[5:7] = np.clip(q[5:7], -1.55, 1.55) + + def act(self, obs, tools): + elapsed = 0 + stage = len(self.primitives) - 1 + stage_start = 0 + for i, primitive in enumerate(self.primitives): + if self.t < elapsed + primitive[4]: + stage = i + stage_start = elapsed + break + elapsed += primitive[4] + + if stage != self.stage: + self.previous_left = self.left.copy() + self.previous_right = self.right.copy() + self.stage = stage + + depth, left_target, right_target, use_servo, _ = self.primitives[stage] + depth = float(np.clip(depth + self.depth_correction, -0.15, 0.55)) + left_target = self._corrected(left_target, True) + right_target = self._corrected(right_target, False) + local_t = self.t - stage_start + blend = min(1.0, float(local_t + 1) / 35.0) + left = (1.0 - blend) * self.previous_left + blend * left_target + right = (1.0 - blend) * self.previous_right + blend * right_target + + if use_servo and blend >= 1.0: + self._servo(tools.image("left_wrist"), left, True) + self._servo(tools.image("right_wrist"), right, False) + + state = np.asarray(obs["low_dim_obs"], dtype=np.float32) + error = depth - (float(state[18]) - self.x0) + raw = np.zeros(20, dtype=np.float32) + raw[0] = np.clip(4.0 * error, -0.18, 0.18) if abs(error) > 0.006 else 0.0 + raw[1] = 0.0 + raw[2] = 0.74 + raw[3] = 0.0 + raw[4:11] = left + raw[11:18] = right + raw[18:20] = 0.0 # Fully open hands, as in the demonstration's reach. + + self.left = left.copy() + self.right = right.copy() + self.t += 1 + return raw diff --git a/policies/reach_target_dual/kimi31pro-s2/episodes.csv b/policies/reach_target_dual/kimi31pro-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f8a61d9f7019ab07f3a32a58860673da721de7c5 --- /dev/null +++ b/policies/reach_target_dual/kimi31pro-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,700,timeout,0 +620001,0,700,timeout,0 +620002,0,700,timeout,0 +620003,1,134,success,0 +620004,1,178,success,0 +620005,0,700,timeout,0 +620006,0,700,timeout,0 +620007,0,700,timeout,0 +620008,0,700,timeout,0 +620009,0,700,timeout,0 +620010,0,700,timeout,0 +620011,0,700,timeout,0 +620012,0,700,timeout,0 +620013,0,700,timeout,0 +620014,0,700,timeout,0 +620015,0,700,timeout,0 +620016,0,700,timeout,0 +620017,0,700,timeout,0 +620018,0,700,timeout,0 +620019,0,700,timeout,0 +620020,0,700,timeout,0 +620021,0,700,timeout,0 +620022,0,700,timeout,0 +620023,0,700,timeout,0 +620024,0,700,timeout,0 +620025,0,700,timeout,0 +620026,0,700,timeout,0 +620027,0,700,timeout,0 +620028,0,700,timeout,0 +620029,0,700,timeout,0 +620030,0,700,timeout,0 +620031,0,700,timeout,0 +620032,0,700,timeout,0 +620033,0,700,timeout,0 +620034,1,271,success,0 +620035,0,700,timeout,0 +620036,0,700,timeout,0 +620037,0,700,timeout,0 +620038,0,700,timeout,0 +620039,0,700,timeout,0 +620040,0,700,timeout,0 +620041,0,700,timeout,0 +620042,0,700,timeout,0 +620043,0,700,timeout,0 +620044,0,700,timeout,0 +620045,0,700,timeout,0 +620046,1,161,success,0 +620047,0,700,timeout,0 +620048,0,700,timeout,0 +620049,0,700,timeout,0 +620050,0,700,timeout,0 +620051,0,700,timeout,0 +620052,0,700,timeout,0 +620053,0,700,timeout,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,0,700,timeout,0 +620058,0,700,timeout,0 +620059,0,700,timeout,0 +620060,1,154,success,0 +620061,0,700,timeout,0 +620062,0,700,timeout,0 +620063,0,700,timeout,0 +620064,0,700,timeout,0 +620065,0,700,timeout,0 +620066,0,700,timeout,0 +620067,0,700,timeout,0 +620068,0,700,timeout,0 +620069,0,700,timeout,0 +620070,0,700,timeout,0 +620071,0,700,timeout,0 +620072,0,700,timeout,0 +620073,1,134,success,0 +620074,0,700,timeout,0 +620075,0,700,timeout,0 +620076,0,700,timeout,0 +620077,0,700,timeout,0 +620078,0,700,timeout,0 +620079,0,700,timeout,0 +620080,0,700,timeout,0 +620081,0,700,timeout,0 +620082,0,700,timeout,0 +620083,1,241,success,0 +620084,0,700,timeout,0 +620085,0,700,timeout,0 +620086,0,700,timeout,0 +620087,0,700,timeout,0 +620088,0,700,timeout,0 +620089,0,700,timeout,0 +620090,0,700,timeout,0 +620091,0,700,timeout,0 +620092,0,700,timeout,0 +620093,0,700,timeout,0 +620094,0,700,timeout,0 +620095,0,700,timeout,0 +620096,0,700,timeout,0 +620097,0,700,timeout,0 +620098,0,700,timeout,0 +620099,0,700,timeout,0 diff --git a/policies/reach_target_dual/kimi31pro-s2/policy.py b/policies/reach_target_dual/kimi31pro-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..759c062007297ba98fb86de910cd10752e256e87 --- /dev/null +++ b/policies/reach_target_dual/kimi31pro-s2/policy.py @@ -0,0 +1,109 @@ +"""Deterministic visual reaching policy for the Unitree G1.""" + +import cv2 +import numpy as np + + +def target_component(image, color): + """Return the largest colored target's center and apparent height.""" + r, g, b = [image[:, :, i].astype(np.float32) for i in range(3)] + if color == "red": + mask = (r > 35) & (r > 1.35 * g) & (r > 1.2 * b) + fallback = np.array([5.0, 13.0, 16.0], dtype=np.float32) + else: + mask = (g > 25) & (g > 1.3 * r) & (g > 1.1 * b) + fallback = np.array([76.0, 3.0, 16.0], dtype=np.float32) + count, _, stats, centers = cv2.connectedComponentsWithStats( + mask.astype(np.uint8), 8 + ) + if count <= 1: + return fallback + index = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA]) + return np.array( + [centers[index, 0], centers[index, 1], stats[index, cv2.CC_STAT_HEIGHT]], + dtype=np.float32, + ) + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + red = target_component(tools.image("head"), "red") + green = target_component(tools.image("head"), "green") + rx, ry = red[0], red[1] + gx, gy = green[0], green[1] + + if rx > 15: + left_roll = 0.6 - 0.03 * (rx - 5) + 0.03 * (ry - 13) + left_pitch = 0.06 * (ry - 13) + left_yaw = -0.2 - 0.04 * (ry - 13) + else: + left_roll = 0.6 - 0.02 * (ry - 13) - 0.03 * (rx - 5) + left_pitch = 0.05 * (ry - 13) - 0.03 * max(rx - 10, 0) + left_yaw = -0.2 + 0.075 * (ry - 13) - 0.03 * max(rx - 10, 0) + + right_roll = 0.6 - 0.02 * (gy - 3) + 0.01 * (gx - 76) + right_pitch = -0.2 + 0.03 * (gy - 3) + right_yaw = 0.2 if gy <= 7 else np.clip(0.2 - 0.1 * (gy - 7), -0.2, 0.2) + if gx < 65: + right_yaw = 0.2 + 0.03 * (65 - gx) + right_pitch -= 0.1 + if gy > 22: + right_yaw -= 0.05 * (gy - 22) + + self.left = np.array( + [ + 0, + np.clip(left_roll, 0, 0.8), + 0, + 0, + -0.5, + np.clip(left_pitch, -0.2, 0.65), + np.clip(left_yaw, -0.6, 0.6), + ], + dtype=np.float32, + ) + self.right = np.array( + [ + 0, + -np.clip(right_roll, 0, 0.8), + 0, + 0, + 0.5, + np.clip(right_pitch, -0.4, 0.7), + right_yaw, + ], + dtype=np.float32, + ) + + p = obs["low_dim_obs"] + approach = np.clip(0.20 + 0.02 * (16.0 - red[2]), 0.14, 0.28) + self.goal = np.array([p[18] + approach, p[19], p[21]], dtype=np.float32) + + def base_servo(self, raw, obs): + p = obs["low_dim_obs"] + x, y, yaw = p[18], p[19], p[21] + ex, ey = self.goal[0] - x, self.goal[1] - y + c, s = np.cos(yaw), np.sin(yaw) + bx, by = c * ex + s * ey, -s * ex + c * ey + vx = 2.0 * bx - 0.35 * p[40] + vy = 2.0 * by - 0.35 * p[41] + speed = np.hypot(vx, vy) + if np.hypot(bx, by) < 0.015: + vx = vy = 0.0 + elif speed < 0.07: + scale = 0.07 / max(speed, 1e-6) + vx *= scale + vy *= scale + raw[0] = np.clip(vx, -0.35, 0.35) + raw[1] = np.clip(vy, -0.20, 0.20) + raw[3] = np.clip(1.5 * (self.goal[2] - yaw) - 0.3 * p[43], -0.3, 0.3) + + def act(self, obs, tools): + raw = self.hold.copy() + raw[18:20] = 0.0 + self.base_servo(raw, obs) + if int(obs["t"]) >= 70: + raw[4:11] = self.left + raw[11:18] = self.right + return raw diff --git a/policies/reach_target_dual/kimi31pro-s3/episodes.csv b/policies/reach_target_dual/kimi31pro-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..e6ee7da618407046ffde08e959a951e88be03d08 --- /dev/null +++ b/policies/reach_target_dual/kimi31pro-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,700,timeout,0 +620001,1,175,success,0 +620002,0,700,timeout,0 +620003,1,186,success,0 +620004,0,700,timeout,0 +620005,0,700,timeout,0 +620006,0,700,timeout,0 +620007,1,161,success,0 +620008,1,154,success,0 +620009,0,700,timeout,0 +620010,1,276,success,0 +620011,1,160,success,0 +620012,0,700,timeout,0 +620013,0,700,timeout,0 +620014,0,700,timeout,0 +620015,0,700,timeout,0 +620016,0,700,timeout,0 +620017,1,445,success,0 +620018,0,700,timeout,0 +620019,1,260,success,0 +620020,1,150,success,0 +620021,1,180,success,0 +620022,0,700,timeout,0 +620023,0,700,timeout,0 +620024,1,317,success,0 +620025,0,700,timeout,0 +620026,0,700,timeout,0 +620027,0,700,timeout,0 +620028,1,544,success,0 +620029,1,325,success,0 +620030,0,700,timeout,0 +620031,0,700,timeout,0 +620032,0,700,timeout,0 +620033,0,700,timeout,0 +620034,1,187,success,0 +620035,1,184,success,0 +620036,1,234,success,0 +620037,1,176,success,0 +620038,1,317,success,0 +620039,1,271,success,0 +620040,1,205,success,0 +620041,1,235,success,0 +620042,0,700,timeout,0 +620043,0,700,timeout,0 +620044,1,176,success,0 +620045,1,376,success,0 +620046,1,165,success,0 +620047,0,700,timeout,0 +620048,1,144,success,0 +620049,1,401,success,0 +620050,1,330,success,0 +620051,0,700,timeout,0 +620052,1,171,success,0 +620053,0,700,timeout,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,0,700,timeout,0 +620058,0,700,timeout,0 +620059,0,700,timeout,0 +620060,1,149,success,0 +620061,0,700,timeout,0 +620062,0,700,timeout,0 +620063,1,238,success,0 +620064,1,187,success,0 +620065,0,700,timeout,0 +620066,0,700,timeout,0 +620067,0,700,timeout,0 +620068,1,340,success,0 +620069,1,254,success,0 +620070,1,332,success,0 +620071,1,190,success,0 +620072,0,700,timeout,0 +620073,1,146,success,0 +620074,1,502,success,0 +620075,0,700,timeout,0 +620076,1,478,success,0 +620077,0,700,timeout,0 +620078,0,700,timeout,0 +620079,1,382,success,0 +620080,0,700,timeout,0 +620081,0,700,timeout,0 +620082,1,142,success,0 +620083,1,154,success,0 +620084,0,700,timeout,0 +620085,0,700,timeout,0 +620086,0,700,timeout,0 +620087,0,700,timeout,0 +620088,0,700,timeout,0 +620089,0,700,timeout,0 +620090,1,191,success,0 +620091,1,471,success,0 +620092,1,266,success,0 +620093,0,700,timeout,0 +620094,0,700,timeout,0 +620095,1,187,success,0 +620096,1,129,success,0 +620097,1,415,success,0 +620098,0,700,timeout,0 +620099,1,189,success,0 diff --git a/policies/reach_target_dual/kimi31pro-s3/policy.py b/policies/reach_target_dual/kimi31pro-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d5ef6d39aefc67765a592444f7c41173678ef6aa --- /dev/null +++ b/policies/reach_target_dual/kimi31pro-s3/policy.py @@ -0,0 +1,157 @@ +"""Deterministic visual reaching policy for the dual-sphere 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.command = self.hold.copy() + self.pitch = [0.0, 0.0] + self.roll = [0.0, 0.0] + self.yaw = [0.0, 0.0] + self.roll_ready = False + self.near = [False, False] + self.near_since = [None, None] + self.last_seen = [-1000, -1000] + self.last_area = [0.0, 0.0] + self.last_centroid = [(42.0, 62.0), (42.0, 72.0)] + self.search_offset = [0.0, 0.0] + self.elbow = [0.0, 0.0] + self.wrist_pitch = [0.0, 0.0] + self.depth_initialized = False + self.initial_centers = self._head_centers(tools.image("head")) + + @staticmethod + def _component(im, color): + a = np.asarray(im, dtype=np.int16) + r, g, b = a[:, :, 0], a[:, :, 1], a[:, :, 2] + if color == "red": + mask = (r > 60) & (r > 1.5 * g) & (r > 1.3 * b) + else: + mask = (g > 35) & (g > 1.3 * r) & (g > 1.15 * b) + n, labels, stats, cents = cv2.connectedComponentsWithStats(mask.astype(np.uint8)) + if n <= 1: + return None + j = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + area = int(stats[j, cv2.CC_STAT_AREA]) + if area < 2: + return None + x, y, w, h = [int(v) for v in stats[j, :4]] + return { + "area": area, + "center": (float(cents[j, 0]), float(cents[j, 1])), + "bbox": (x, y, w, h), + } + + def _head_centers(self, im): + out = [] + for color in ("red", "green"): + det = self._component(im, color) + if det is None: + out.append(None) + continue + cx, cy = det["center"] + x, y, w, h = det["bbox"] + # A clipped sphere's centroid is biased toward the image. Estimate + # its center from the visible outer edge and its apparent radius. + if x == 0 and h >= 5: + cx = x + w - 0.5 * h + if x + w >= 84 and h >= 5: + cx = x + 0.5 * h + if y == 0 and w >= 5: + cy = y + h - 0.5 * w + out.append((cx, cy)) + return out + + def act(self, obs, tools): + t = int(obs["t"]) + raw = np.zeros(20, dtype=np.float32) + raw[2] = 0.74 + raw[18] = 1.0 if self.near[0] else 0.0 + raw[19] = 1.0 if self.near[1] else 0.0 + if 20 <= t < 60: + raw[0] = 0.25 + + if t >= 65 and not self.roll_ready: + centers = self._head_centers(tools.image("head")) + for side in range(2): + if centers[side] is None: + centers[side] = self.initial_centers[side] + if centers[0] is not None: + self.roll[0] = float(np.clip((15.0 - centers[0][0]) / 55.0, -0.35, 0.60)) + if centers[1] is not None: + self.roll[1] = float(np.clip((65.0 - centers[1][0]) / 55.0, -0.60, 0.60)) + self.roll_ready = True + + if t == 90: + early = [ + self._component(tools.image("left_wrist"), "red"), + self._component(tools.image("right_wrist"), "green"), + ] + if max(0 if d is None else d["area"] for d in early) < 1500: + self.elbow = [-0.30, -0.30] + self.wrist_pitch = [0.30, 0.30] + self.depth_initialized = True + + if t >= 90: + for side, (camera, color) in enumerate((("left_wrist", "red"), ("right_wrist", "green"))): + det = self._component(tools.image(camera), color) + if self.near[side]: + if det is not None and det["area"] < 4300 and t - self.near_since[side] > 15: + self.near[side] = False + else: + continue + if det is None: + # Once a large sphere passes out of the wrist view, keep + # the arm still: this is often the actual contact posture. + if t - self.last_seen[side] < 12 and self.last_area[side] > 1800: + self.near[side] = True + self.near_since[side] = t + continue + area = det["area"] + x, y = det["center"] + self.last_seen[side] = t + self.last_area[side] = area + self.last_centroid[side] = (x, y) + if area >= 5700: + self.near[side] = True + self.near_since[side] = t + continue + + if t >= 140 and area > 800 and abs(x - 42.0) < 14 and abs(y - 42.0) < 16: + extension = 0.0025 + self.elbow[side] = min(1.0, self.elbow[side] + extension) + self.wrist_pitch[side] = max(-1.0, self.wrist_pitch[side] - extension) + + # Image Jacobian for small shoulder motions near the reaching + # posture. Positive pitch raises the target in either view; + # positive signed roll moves it to the right. + if side == 0: + dp = (y - 42.0) / 195.0 + dr = -(x - 42.0 - 65.0 * dp) / 95.0 + else: + dp = (y - 42.0) / 155.0 + dr = -(x - 42.0 + 45.0 * dp) / 125.0 + gain = 0.055 + self.pitch[side] += float(np.clip(gain * dp, -0.006, 0.006)) + dyaw = -(x - 42.0) / 165.0 + self.yaw[side] += float(np.clip(gain * dyaw, -0.006, 0.006)) + self.pitch[side] = float(np.clip(self.pitch[side], -0.65, 0.65)) + self.yaw[side] = float(np.clip(self.yaw[side], -0.85, 0.85)) + + desired = np.zeros(14, dtype=np.float32) + desired[0] = self.pitch[0] + desired[1] = self.roll[0] + desired[2] = self.yaw[0] + desired[3] = self.elbow[0] + desired[5] = self.wrist_pitch[0] + desired[7] = self.pitch[1] + desired[8] = self.roll[1] + desired[9] = self.yaw[1] + desired[10] = self.elbow[1] + desired[12] = self.wrist_pitch[1] + self.command[4:18] += np.clip(desired - self.command[4:18], -0.018, 0.018) + raw[4:18] = self.command[4:18] + return raw diff --git a/policies/reach_target_dual/opus-s1/episodes.csv b/policies/reach_target_dual/opus-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..99f119df995533cea811610feccf4105fd3c82b0 --- /dev/null +++ b/policies/reach_target_dual/opus-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,495,success,0 +620001,1,451,success,0 +620002,1,329,success,0 +620003,1,341,success,0 +620004,1,339,success,0 +620005,1,260,success,0 +620006,1,351,success,0 +620007,1,494,success,0 +620008,0,700,timeout,0 +620009,1,424,success,0 +620010,1,354,success,0 +620011,1,421,success,0 +620012,1,255,success,0 +620013,1,436,success,0 +620014,1,497,success,0 +620015,1,242,success,0 +620016,1,521,success,0 +620017,1,309,success,0 +620018,1,582,success,0 +620019,1,459,success,0 +620020,1,295,success,0 +620021,1,349,success,0 +620022,0,700,timeout,0 +620023,0,700,timeout,0 +620024,0,700,timeout,0 +620025,0,700,timeout,0 +620026,0,700,timeout,0 +620027,1,368,success,0 +620028,1,251,success,0 +620029,1,445,success,0 +620030,1,495,success,0 +620031,0,700,timeout,0 +620032,1,420,success,0 +620033,0,700,timeout,0 +620034,1,257,success,0 +620035,1,347,success,0 +620036,0,700,timeout,0 +620037,1,527,success,0 +620038,0,700,timeout,0 +620039,1,342,success,0 +620040,0,700,timeout,0 +620041,1,256,success,0 +620042,1,346,success,0 +620043,0,700,timeout,0 +620044,0,700,timeout,0 +620045,1,258,success,0 +620046,1,224,success,0 +620047,1,495,success,0 +620048,1,437,success,0 +620049,0,700,timeout,0 +620050,0,700,timeout,0 +620051,1,333,success,0 +620052,0,700,timeout,0 +620053,1,349,success,0 +620054,0,700,timeout,0 +620055,1,362,success,0 +620056,1,384,success,0 +620057,1,258,success,0 +620058,1,459,success,0 +620059,1,352,success,0 +620060,1,269,success,0 +620061,1,571,success,0 +620062,1,530,success,0 +620063,1,428,success,0 +620064,0,700,timeout,0 +620065,0,700,timeout,0 +620066,1,293,success,0 +620067,1,306,success,0 +620068,1,372,success,0 +620069,0,700,timeout,0 +620070,1,429,success,0 +620071,0,700,timeout,0 +620072,1,308,success,0 +620073,1,286,success,0 +620074,1,455,success,0 +620075,0,700,timeout,0 +620076,1,377,success,0 +620077,1,337,success,0 +620078,1,457,success,0 +620079,1,324,success,0 +620080,0,700,timeout,0 +620081,0,700,timeout,0 +620082,1,245,success,0 +620083,1,451,success,0 +620084,0,700,timeout,0 +620085,1,403,success,0 +620086,1,410,success,0 +620087,1,420,success,0 +620088,1,410,success,0 +620089,1,436,success,0 +620090,1,422,success,0 +620091,1,334,success,0 +620092,1,253,success,0 +620093,0,700,timeout,0 +620094,1,326,success,0 +620095,0,700,timeout,0 +620096,0,700,timeout,0 +620097,1,256,success,0 +620098,1,395,success,0 +620099,0,700,timeout,0 diff --git a/policies/reach_target_dual/opus-s1/policy.py b/policies/reach_target_dual/opus-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..7c3d7ccb59f1af72d768f4df6d01611b12c29698 --- /dev/null +++ b/policies/reach_target_dual/opus-s1/policy.py @@ -0,0 +1,600 @@ +"""Dual reach policy: touch the red sphere with the left hand, green with the right. + +Pipeline: locate both spheres in the head camera (colour blobs -> 3D by +triangulating all views with a calibrated pinhole model and the known sphere +radius; extra viewpoints for spheres outside the view), walk to a reaching +station, solve arm IK (G1 kinematics) with integral action against gravity +droop, and search along the camera ray until each visible sphere lights up. +""" + +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} +TORSO = np.array([-0.0039635, 0, 0.054]) + + +def chain(side): + s = 1 if side == "left" 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"), + ] + + +CHAINS = {"left": chain("left"), "right": chain("right")} + + +def fk(q, side, tip): + p = TORSO.copy() + R = np.eye(3) + for (xyz, R0, ax), qi in zip(CHAINS[side], q): + p = p + R @ xyz + R = R @ R0 @ AX[ax](qi) + return p + R @ tip + + +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]) +TIP = np.array([0.10, 0.0, 0.0]) + + +def limits(side): + if side == "left": + return LO, HI + return np.minimum(LO * MIR, HI * MIR), np.maximum(LO * MIR, HI * MIR) + + +STARTS = [np.array(v) for v in ([-0.6, 0.2, 0.0, 0.3], [-1.2, 0.3, 0.0, -0.3], + [-0.2, 0.1, 0.0, 0.9], [-0.8, 0.4, 0.4, 0.2])] + + +def ik(target, side, q0=None, lam=0.01): + s = 1 if side == "left" else -1 + qnom = np.array([-0.6, 0.2 * s, 0.0, 0.3, 0, 0, 0]) + lo, hi = limits(side) + idx = [0, 1, 2, 3] + + def res(x): + q = qnom.copy() + q[idx] = x + return np.r_[fk(q, side, TIP) - target, lam * (x - qnom[idx])] + + inits = [st * np.array([1, s, s, 1]) for st in STARTS] + if q0 is not None: + inits = [np.asarray(q0)[idx]] + best = None + for x0 in inits: + x0 = np.clip(x0, lo[idx] + 1e-3, hi[idx] - 1e-3) + sol = least_squares(res, x0, bounds=(lo[idx], hi[idx])) + if best is None or sol.cost < best.cost - 1e-9: + best = sol + q = qnom.copy() + q[idx] = best.x + return q, float(np.linalg.norm(fk(q, side, TIP) - target)) + + +# --------------------------------------------------------------------- camera + +CAM = dict(f=89.365, pos=np.array([0.0302, 0.0156, 0.4642]), pitch=1.006, + yaw=-0.0069, roll=-0.0068, R=0.0475) + + +def cam_R(): + p, yaw, roll = CAM["pitch"], CAM["yaw"], CAM["roll"] + z = np.array([np.cos(p), 0, -np.sin(p)]) + x = np.array([0, -1.0, 0]) + y = np.cross(z, x) + R = np.c_[x, y, z] + return Rz(yaw) @ R @ Rz(roll) + + +CAMR = cam_R() + + +def pix_to_pelvis(u, v, r): + f, Rs = CAM["f"], CAM["R"] + d = Rs * np.sqrt(f ** 2 / r ** 2 + 1) + ray = np.array([(u - 41.5) / f, (v - 41.5) / f, 1.0]) + ray /= np.linalg.norm(ray) + return CAMR @ (ray * d) + CAM["pos"] + + +def pelvis_to_world(pt, pose): + return Rz(pose[3]) @ pt + pose[:3] + + +def world_to_pelvis(pt, pose): + return Rz(pose[3]).T @ (pt - pose[:3]) + + +# --------------------------------------------------------------------- vision + +def colour_masks(im): + im = im.astype(np.int16) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + red = (r > 50) & (r > g + 35) & (r > b + 35) + green = (g > 50) & (g > r + 30) & (g > b + 15) + return red, green + + +def blob(mask, img_ch): + n, lab, stats, cent = cv2.connectedComponentsWithStats(mask.astype(np.uint8), 8) + if n <= 1: + return None + i = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + area = int(stats[i, cv2.CC_STAT_AREA]) + if area < 4: + return None + x, y, w, h = stats[i, :4] + H, W = mask.shape + edge = bool(x == 0 or y == 0 or x + w >= W or y + h >= H) + cs, _ = cv2.findContours((lab == i).astype(np.uint8), cv2.RETR_EXTERNAL, + cv2.CHAIN_APPROX_NONE) + pts = cs[0][:, 0, :].astype(float) + keep = (pts[:, 0] > 0) & (pts[:, 1] > 0) & (pts[:, 0] < W - 1) & (pts[:, 1] < H - 1) + p = pts[keep] if keep.sum() >= 5 else pts + A = np.c_[2 * p[:, 0], 2 * p[:, 1], np.ones(len(p))] + sol, *_ = np.linalg.lstsq(A, (p ** 2).sum(1), rcond=None) + cx, cy = sol[0], sol[1] + rad = np.sqrt(max(sol[2] + cx ** 2 + cy ** 2, 0)) + 0.5 + m = lab == i + return dict(area=area, cx=float(cx), cy=float(cy), r=float(rad), edge=edge, + ninner=int(keep.sum()), bright=float(np.percentile(img_ch[m], 90))) + + +def lit_count(im, colour): + """Pixels of the lit (bright, saturated) sphere colour.""" + im = im.astype(np.int16) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + if colour == "red": + return int(((r > 215) & (g < 90) & (b < 90)).sum()) + return int(((g > 215) & (r < 110) & (b < 110)).sum()) + + +def detect(im): + red, green = colour_masks(im) + return {"red": blob(red, im[..., 0]), "green": blob(green, im[..., 1])} + + +# --------------------------------------------------------------------- policy + +STANDOFF = 0.25 # desired sphere distance in front of the pelvis (at pelvis height) +VIEW_DIST = 0.32 # horizontal pelvis-sphere distance for a dedicated look +YAW_GAIN = 2.5 +YAW_MAX = 0.8 +TUCK = np.array([0.0, 0.25, 0.0, 1.3, 0.0, 0.0, 0.0]) # arms out of the head view +# FK-frame offset at which each hand lights its sphere (measured by scanning) +BIAS = {"left": np.array([0.0, 0.0, 0.0]), "right": np.array([0.0, 0.0, 0.0])} +R_WEIGHT = 0.5 # weight of the apparent radius against the pixel position +KI = 0.05 # per-step integral gain on arm joint tracking error +DEFAULT = {"red": np.array([0.45, 0.2, 0.08]), "green": np.array([0.45, -0.2, 0.08])} +SIDE = {"left": "red", "right": "green"} +ARM = {"red": "left", "green": "right"} +DWELL = 6 +SOLO_T = 200 +USE_SOLO = False +STATION_YAW = 0.6 # max heading change of the reaching station +LOOK_N = 8 +SOLO_Y = 0.12 # lateral offset of a sphere in the single-arm station + + +def search_offsets(): + pts = [] + s = 0.025 + for i in range(-2, 3): + for j in range(-3, 4): + for k in range(-3, 4): + p = np.array([i * s, j * s, k * s]) + if (p[0] / 0.05) ** 2 + (p[1] / 0.075) ** 2 + (p[2] / 0.075) ** 2 <= 1.0001: + pts.append(p) + pts.sort(key=lambda p: (round(float(np.linalg.norm(p)), 4), float(np.arctan2(p[2], p[1])), p[0])) + return pts + + +def ray_offsets(): + """Search pattern (depth along the camera ray, then sideways): the image + position of a sphere is precise, its depth is not.""" + out = [(t, 0.0, 0.0) for t in (0.0, 0.03, -0.03, 0.06, -0.06, 0.09, 0.12, -0.09, 0.15)] + for t in (0.0, 0.03, -0.03, 0.06, 0.09, -0.06, 0.12): + for a, b in ((0.03, 0), (-0.03, 0), (0, 0.03), (0, -0.03)): + out.append((t, a, b)) + return out + + +OFFSETS = ray_offsets() + + +def ray_frame(S): + ray = S - CAM["pos"] + ray /= np.linalg.norm(ray) + e1 = np.cross(ray, [0, 0, 1.0]) + e1 /= np.linalg.norm(e1) + e2 = np.cross(e1, ray) + return ray, e1, e2 + + +def offset_vec(S, c): + ray, e1, e2 = ray_frame(S) + return c[0] * ray + c[1] * e1 + c[2] * e2 + + +def plausible(P): + return 0.1 < P[0] < 1.0 and abs(P[1]) < 0.7 and -0.35 < P[2] < 0.45 + + +def wrap(a): + return (a + np.pi) % (2 * np.pi) - np.pi + + +def project(P): + """Pelvis-frame point -> head pixel (u, v) and pixel radius.""" + c = CAMR.T @ (P - CAM["pos"]) + if c[2] <= 0.05: + return None + f = CAM["f"] + return 41.5 + f * c[0] / c[2], 41.5 + f * c[1] / c[2], f * CAM["R"] / c[2] + + +def visible(P, margin=0.0): + p = project(P) + if p is None: + return False + u, v, r = p + m = r * margin + return m - 0.5 <= u <= 83.5 - m and m - 0.5 <= v <= 83.5 - m + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float64) + self.world = {} + self.qual = {"red": 0, "green": 0} + self.corr = {"red": np.zeros(3), "green": np.zeros(3)} # world-frame corrections + self.qcmd = {"left": TUCK.copy(), "right": TUCK * MIR} + self.log = [] + self.home = self.pose(obs) + self.queue = [("settle", 25), ("look", LOOK_N, "start")] + self.task = None + self.phase = "plan" + self.active = () + self.srch = {} + self.solo_est = {} + self.hist = {"red": [], "green": []} + self.qint = {"left": np.zeros(7), "right": np.zeros(7)} + + # ------------------------------------------------------------ helpers + def pose(self, obs): + return np.asarray(obs["low_dim_obs"][18:22], dtype=np.float64) + + def observe(self, obs, tools, acc): + det = detect(tools.image("head")) + pose = self.pose(obs) + for k in ("red", "green"): + b = det[k] + if b is None or b["r"] <= 2 or b["ninner"] < 6: + continue + P = pix_to_pelvis(b["cx"], b["cy"], b["r"]) + if not plausible(P): + continue + acc[k][0 if b["edge"] else 1].append(pelvis_to_world(P, pose)) + self.hist[k].append((pose.copy(), b["cx"], b["cy"], b["r"], b["edge"])) + + def triangulate(self, k, P0, full_only): + rows = [h for h in self.hist[k] if not (full_only and h[4])] + if not rows: + return P0 + + def res(P): + out = [] + for pose, u, v, r, edge in rows: + p = project(world_to_pelvis(P, pose)) + w = 0.3 if edge else 1.0 + if p is None: + out += [10.0, 10.0, 10.0] + else: + out += [w * (p[0] - u), w * (p[1] - v), w * R_WEIGHT * (p[2] - r)] + return out + + sol = least_squares(res, P0, loss="soft_l1", f_scale=1.0) + return sol.x + + def fuse(self, acc): + for k in ("red", "green"): + part, full = acc[k] + if len(full) >= 3: + self.world[k] = self.triangulate(k, np.median(np.array(full), 0), False) + self.qual[k] = 2 + elif len(part) >= 3 and self.qual[k] <= 1: + self.world[k] = self.triangulate(k, np.median(np.array(part), 0), False) + self.qual[k] = 1 + + def target_world(self, k, pose=None): + if k in self.world: + return self.world[k] + return pelvis_to_world(DEFAULT[k], self.home) + + def xd(self, p): + return float(np.clip(STANDOFF + 0.3 * (p[2] - self.home[2]), 0.2, 0.36)) + + def clip_station(self, g): + rel = world_to_pelvis(np.r_[g, self.home[2]], self.home) + rel[0] = np.clip(rel[0], -0.1, 0.4) + rel[1] = np.clip(rel[1], -0.3, 0.3) + return pelvis_to_world(rel, self.home)[:2] + + def clip_yaw(self, th, lim): + return self.home[3] + np.clip(wrap(th - self.home[3]), -lim, lim) + + def station(self): + red, green = self.target_world("red"), self.target_world("green") + mid = 0.5 * (red + green) + d = mid[:2] - self.home[:2] + th_mid = self.clip_yaw(np.arctan2(d[1], d[0]), 0.5) + xd = [self.xd(red), self.xd(green)] + + def res(v): + st = np.array([v[0], v[1], self.home[2], v[2]]) + a = world_to_pelvis(red, st) + b = world_to_pelvis(green, st) + return [a[0] - xd[0], b[0] - xd[1], 0.7 * (a[1] + b[1]), 0.1 * (v[2] - th_mid)] + + g0 = mid[:2] - np.mean(xd) * np.array([np.cos(th_mid), np.sin(th_mid)]) + sol = least_squares(res, np.r_[g0, th_mid]) + th = self.clip_yaw(sol.x[2], STATION_YAW) + if abs(wrap(th - sol.x[2])) > 1e-6: + # heading was clipped: re-solve the position for the clipped heading + def res2(v): + return res([v[0], v[1], th])[:3] + sol2 = least_squares(res2, sol.x[:2]) + return self.clip_station(sol2.x), th + return self.clip_station(sol.x[:2]), th + + def solo_station(self, k): + """Station where sphere k sits in front of its own arm, inside the head view.""" + P = self.target_world(k) + s = 1 if k == "red" else -1 + xd = self.xd(P) + d = P[:2] - self.home[:2] + th = self.clip_yaw(np.arctan2(d[1], d[0]), 1.0) + + def res(v): + st = np.array([v[0], v[1], self.home[2], v[2]]) + a = world_to_pelvis(P, st) + return [a[0] - xd, a[1] - s * SOLO_Y, 0.05 * wrap(v[2] - th)] + + g0 = P[:2] - xd * np.array([np.cos(th), np.sin(th)]) + sol = least_squares(res, np.r_[g0, th]) + return self.clip_station(sol.x[:2]), self.clip_yaw(sol.x[2], 1.0) + + def viewpoint(self, k): + P = self.target_world(k) + d = P[:2] - self.home[:2] + u = d / max(np.linalg.norm(d), 1e-6) + g = self.clip_station(P[:2] - VIEW_DIST * u) + yaw = self.clip_yaw(np.arctan2(P[1] - g[1], P[0] - g[0]), 1.0) + return g, yaw + + def both_visible(self, g, th): + st = np.array([g[0], g[1], self.home[2], th]) + return all(visible(world_to_pelvis(self.target_world(k), st), 0.3) for k in ("red", "green")) + + # ------------------------------------------------------------ planning + def plan(self, tag, pose): + if tag == "start": + g, th = self.station() + if self.both_visible(g, th) or not USE_SOLO: + self.mode = "joint" + self.pending = [k for k in ("red", "green") if self.qual[k] < 2] + tag = "scan" + else: + self.mode = "solo" + self.pending = ["red", "green"] + tag = "solo" + if tag == "scan": + while self.pending: + k = self.pending.pop(0) + if self.qual[k] >= 2: + continue + g, yaw = self.viewpoint(k) + self.queue += [("goto", g, yaw), ("settle", 15), ("look", LOOK_N, "scan")] + return + g, th = self.station() + self.queue += [("goto", g, th), ("settle", 20), ("look", LOOK_N, "reach")] + return + if tag == "solo": + if self.pending: + k = self.pending.pop(0) + self.solo_est[k] = self.target_world(k).copy() + g, th = self.solo_station(k) + self.queue += [("goto", g, th), ("settle", 15), ("look", LOOK_N, "solo_" + k)] + return + g, th = self.station() + self.queue += [("goto", g, th), ("settle", 15), ("look", LOOK_N, "reach")] + return + if tag.startswith("solo_"): + k = tag[5:] + # the look may have refined the estimate: re-station once if it moved a lot + prev = self.solo_est.get(k) + if prev is not None and np.linalg.norm(self.target_world(k) - prev) > 0.04: + self.solo_est[k] = None + g, th = self.solo_station(k) + self.queue += [("goto", g, th), ("settle", 10), ("look", LOOK_N, tag)] + return + self.start_reach(pose, (ARM[k],), solo=True) + return + if tag == "reach": + self.start_reach(pose, ("left", "right")) + + def start_reach(self, pose, arms, solo=False): + self.qgoal = {} + self.active = arms + self.solo = solo + for side in arms: + k = SIDE[side] + P = world_to_pelvis(self.target_world(k) + self.corr[k], pose) + q, e = ik(P + BIAS[side], side) + self.qgoal[side] = q + self.log.append((side, P, q, e)) + self.srch[side] = dict(center=np.zeros(3), cur=np.zeros(3), idx=0, cnt=0, lit_t=-1, lost=0, + q=q.copy(), nlit=0) + self.qstart = {s: self.qcmd[s].copy() for s in ("left", "right")} + self.phase = "reach" + self.treach = None + + def lit(self, tools): + im = tools.image("head") + det = detect(im) + return ({k: lit_count(im, k) >= 3 for k in ("red", "green")}, + {k: det[k] is not None and det[k]["area"] >= 8 for k in ("red", "green")}) + + # ------------------------------------------------------------------ act + def act(self, obs, tools): + try: + raw = self._act(obs, tools) + self.last_raw = raw + return raw + except Exception: # never crash an episode: hold the last command + raw = getattr(self, "last_raw", None) + if raw is None: + raw = self.hold.copy() + raw = np.array(raw, dtype=np.float64) + raw[0] = raw[1] = raw[3] = 0.0 + return raw + + def _act(self, obs, tools): + t = int(obs["t"]) + pose = self.pose(obs) + self.last_obs = obs + raw = self.hold.copy() + raw[0] = raw[1] = raw[3] = 0.0 + raw[2] = 0.74 + if self.phase == "plan": + if self.task is None and self.queue: + self.task = list(self.queue.pop(0)) + [t] + if self.task[0] == "look": + self.acc = {"red": ([], []), "green": ([], [])} + task = self.task + kind = task[0] + if kind == "look": + self.observe(obs, tools, self.acc) + if t - task[-1] + 1 >= task[1]: + self.fuse(self.acc) + self.task = None + self.plan(task[2], pose) + elif kind == "settle": + if t - task[-1] >= task[1]: + self.task = None + elif kind == "goto": + g, th = task[1], task[2] + err = world_to_pelvis(np.r_[g, pose[2]], pose)[:2] + eth = wrap(th - pose[3]) + dist = np.linalg.norm(err) + if (dist < 0.02 and abs(eth) < 0.04) or t - task[-1] > 250: + self.task = None + else: + if dist >= 0.02: + v = err * 1.5 + sp = np.linalg.norm(v) + v = v / max(sp, 1e-9) * np.clip(sp, 0.08, 0.25) + raw[0], raw[1] = v + w = np.clip(YAW_GAIN * eth, -YAW_MAX, YAW_MAX) + if abs(eth) >= 0.04 and abs(w) < 0.2: + w = 0.2 * np.sign(eth) + raw[3] = w + elif self.phase == "reach": + if self.treach is None: + self.treach = t + a = min(1.0, (t - self.treach) / 40.0) + for side in ("left", "right"): + goal = self.qgoal[side] if side in self.active else (TUCK if side == "left" else TUCK * MIR) + self.qcmd[side] = (1 - a) * self.qstart[side] + a * goal + if a >= 1.0: + self.phase = "search" + self.tsearch = t + elif self.phase == "search": + self.search_step(t, pose, tools) + # integral action on the joint targets removes the gravity droop of the + # position-controlled arms + ld = obs["low_dim_obs"] + for side, sl, qm in (("left", slice(4, 11), ld[0:7]), ("right", slice(11, 18), ld[9:16])): + q = self.qcmd[side] + if side in self.active and self.phase == "search": + self.qint[side] = np.clip(self.qint[side] + KI * (q - qm), -0.35, 0.35) + else: + self.qint[side] *= 0.9 + lo, hi = limits(side) + raw[sl] = np.clip(q + self.qint[side], lo, hi) + return raw + + def search_step(self, t, pose, tools): + lit, seen = self.lit(tools) + if getattr(self, "debug", None) is not None: + ld = self.last_obs["low_dim_obs"] + for side, qm in (("left", ld[0:7]), ("right", ld[9:16])): + k = SIDE[side] + S = world_to_pelvis(self.target_world(k), pose) + self.debug.append((t, side, fk(np.asarray(qm, float), side, TIP) - S, lit[k], seen[k])) + for side in self.active: + S = self.srch[side] + k = SIDE[side] + if lit[k]: + S["lost"] = 0 + S["lit_t"] = t + S["nlit"] += 1 + S["center"] = S["cur"] + S["idx"] = 0 + S["cnt"] = 0 + continue + S["lost"] += 1 + if S["lit_t"] >= 0 and S["lost"] < 12: + continue # recently lit: wait before searching again + if not seen[k] and not self.solo: + continue # cannot observe this sphere: hold the calibrated target + S["cnt"] += 1 + if S["cnt"] >= DWELL: + S["cnt"] = 0 + S["idx"] = (S["idx"] + 1) % len(OFFSETS) + P = world_to_pelvis(self.target_world(k) + self.corr[k], pose) + off = S["center"] + offset_vec(P, OFFSETS[S["idx"]]) + S["cur"] = off + q, e = ik(P + BIAS[side] + off, side, S["q"]) + S["q"] = q + self.qcmd[side] = q + if self.solo: + side = self.active[0] + S = self.srch[side] + k = SIDE[side] + done = S["nlit"] >= 6 or t - self.tsearch > SOLO_T + if done: + if S["nlit"] >= 6: + self.corr[k] = self.corr[k] + Rz(pose[3]) @ S["center"] + self.log.append(("solo", k, S["nlit"], S["center"])) + self.active = () + self.phase = "plan" + self.qcmd[side] = TUCK.copy() if side == "left" else TUCK * MIR + self.plan("solo", pose) diff --git a/policies/reach_target_dual/opus-s2/episodes.csv b/policies/reach_target_dual/opus-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..c00ab25e2d7f2911cda22337099d5158adf6320c --- /dev/null +++ b/policies/reach_target_dual/opus-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,256,success,0 +620001,1,218,success,0 +620002,1,197,success,0 +620003,1,225,success,0 +620004,1,230,success,0 +620005,1,228,success,0 +620006,1,211,success,0 +620007,1,223,success,0 +620008,1,227,success,0 +620009,1,252,success,0 +620010,1,225,success,0 +620011,1,234,success,0 +620012,1,234,success,0 +620013,1,214,success,0 +620014,1,211,success,0 +620015,1,233,success,0 +620016,1,211,success,0 +620017,1,206,success,0 +620018,1,207,success,0 +620019,1,212,success,0 +620020,1,205,success,0 +620021,1,232,success,0 +620022,1,224,success,0 +620023,1,196,success,0 +620024,1,213,success,0 +620025,1,275,success,0 +620026,1,211,success,0 +620027,1,199,success,0 +620028,1,210,success,0 +620029,1,223,success,0 +620030,1,212,success,0 +620031,1,205,success,0 +620032,1,244,success,0 +620033,1,207,success,0 +620034,1,220,success,0 +620035,1,235,success,0 +620036,1,218,success,0 +620037,1,237,success,0 +620038,1,221,success,0 +620039,1,234,success,0 +620040,1,221,success,0 +620041,1,208,success,0 +620042,1,203,success,0 +620043,1,242,success,0 +620044,1,242,success,0 +620045,1,229,success,0 +620046,1,187,success,0 +620047,1,236,success,0 +620048,1,241,success,0 +620049,1,222,success,0 +620050,1,231,success,0 +620051,1,232,success,0 +620052,0,700,timeout,0 +620053,1,207,success,0 +620054,1,214,success,0 +620055,1,204,success,0 +620056,1,234,success,0 +620057,1,192,success,0 +620058,1,236,success,0 +620059,1,206,success,0 +620060,1,218,success,0 +620061,1,216,success,0 +620062,1,209,success,0 +620063,1,242,success,0 +620064,1,209,success,0 +620065,1,210,success,0 +620066,1,195,success,0 +620067,1,214,success,0 +620068,1,222,success,0 +620069,1,198,success,0 +620070,1,237,success,0 +620071,1,226,success,0 +620072,1,226,success,0 +620073,1,224,success,0 +620074,1,244,success,0 +620075,1,229,success,0 +620076,1,212,success,0 +620077,1,231,success,0 +620078,1,257,success,0 +620079,1,221,success,0 +620080,1,212,success,0 +620081,1,245,success,0 +620082,1,153,success,0 +620083,1,209,success,0 +620084,1,249,success,0 +620085,1,203,success,0 +620086,1,224,success,0 +620087,1,205,success,0 +620088,1,212,success,0 +620089,1,301,success,0 +620090,1,231,success,0 +620091,1,196,success,0 +620092,1,194,success,0 +620093,1,239,success,0 +620094,1,203,success,0 +620095,1,239,success,0 +620096,1,203,success,0 +620097,1,194,success,0 +620098,1,230,success,0 +620099,1,211,success,0 diff --git a/policies/reach_target_dual/opus-s2/g1reach_geom.py b/policies/reach_target_dual/opus-s2/g1reach_geom.py new file mode 100644 index 0000000000000000000000000000000000000000..cf8d0f97031ee5d6b8f89f26eb3ccccbc62fbfe2 --- /dev/null +++ b/policies/reach_target_dual/opus-s2/g1reach_geom.py @@ -0,0 +1,193 @@ +"""Camera, floor and arm geometry for the G1 reach policy (hand-written models).""" + +import numpy as np + +# ---------------------------------------------------------------- head camera +# Fitted from the floor checkerboard (0.2 m squares) in the head images. +F_PX = 68.51 # focal length in pixels (84x84 image) +K1 = -0.0225 # radial term (undistorted = distorted * (1 + K1 r^2)) +CAM_PITCH = 1.104 # rad, pitched down +CAM_ROLL = -0.012 +CAM_YAW = -0.005 # relative to the pelvis yaw +CAM_H_ABOVE_PELVIS = 0.349 # camera height above the pelvis z (world) +# camera position in the arm-FK frame (fitted against hand observations) +CAM_FK = np.array([0.146, 0.0, 0.382]) +NADIR = None + + +def _rot(th, ph, ps): + cy, sy = np.cos(ps), np.sin(ps) + cp, sp = np.cos(th), np.sin(th) + cr, sr = np.cos(ph), np.sin(ph) + Rz = np.array([[cy, -sy, 0], [sy, cy, 0], [0, 0, 1]]) + Ry = np.array([[cp, 0, sp], [0, 1, 0], [-sp, 0, cp]]) + Rx = np.array([[1, 0, 0], [0, cr, -sr], [0, sr, cr]]) + return Rz @ Ry @ Rx + + +R_CAM = _rot(CAM_PITCH, CAM_ROLL, CAM_YAW) # camera -> yaw-aligned body frame + + +def pixel_ray(u, v): + """Unit ray (body frame, yaw-aligned, z up) through pixel (u, v).""" + xd = (u - 42.0) / F_PX + yd = (v - 42.0) / F_PX + rr = xd * xd + yd * yd + xu = xd * (1 + K1 * rr) + yu = yd * (1 + K1 * rr) + d = R_CAM @ np.array([1.0, -xu, -yu]) + return d / np.linalg.norm(d) + + +def project(p_cam): + """Pixel of point p (body frame, relative to the camera).""" + d = R_CAM.T @ p_cam + if d[0] <= 1e-6: + return None + xu, yu = -d[1] / d[0], -d[2] / d[0] + rr = xu * xu + yu * yu + xd, yd = xu / (1 + K1 * rr), yu / (1 + K1 * rr) + return 42.0 + F_PX * xd, 42.0 + F_PX * yd + + +def floor_point(u, v, cam_h): + """Floor point (relative to camera, body frame) seen at pixel (u, v).""" + d = pixel_ray(u, v) + if d[2] >= -1e-3: + return None + return d * (cam_h / -d[2]) + + +# ---------------------------------------------------------------- wrist cameras +# Fitted from the floor checkerboard in the wrist images at the default arm pose: +# the camera looks 0.744 rad below the wrist-yaw link x axis. +WR_F = 73.0 +SPHERE_R = 0.05 + + +def _ry_(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +R_LC = _ry_(0.744) # wrist camera (fwd, left, up) -> wrist-yaw link frame + + +def wrist_dir(u, v): + d = np.array([1.0, -(u - 42.0) / WR_F, -(v - 42.0) / WR_F]) + return d / np.linalg.norm(d) + + +def wrist_sphere_cam(u, v, r): + """Sphere centre in wrist camera coordinates from its image circle.""" + D = SPHERE_R / np.sin(np.arctan(max(r, 1.0) / WR_F)) + return D * wrist_dir(u, v) + + +# ---------------------------------------------------------------- arm FK +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]) +_AX = {'x': _rx, 'y': _ry, 'z': _rz} +_AXV = {'x': np.array([1.0, 0, 0]), 'y': np.array([0, 1.0, 0]), 'z': np.array([0, 0, 1.0])} + + +def _chain(side): + s = 1.0 if side == 'L' else -1.0 + return [ + ((0.0039563, s * 0.10022, 0.23778), _rpy(s * 0.27931, 5.4949e-05, -s * 0.00019159), 'y'), + ((0.0, s * 0.038, -0.013831), _rpy(-s * 0.27925, 0, 0), 'x'), + ((0.0, s * 0.00624, -0.1032), np.eye(3), 'z'), + ((0.015783, 0, -0.080518), np.eye(3), 'y'), + ((0.100, s * 0.00188791, -0.010), np.eye(3), 'x'), + ((0.038, 0, 0), np.eye(3), 'y'), + ((0.046, 0, 0), np.eye(3), 'z'), + ] + + +CHAINS = {'L': _chain('L'), 'R': _chain('R')} +TOOL = np.array([0.153, -0.017, 0.020]) # fingertip midpoint in the wrist-yaw frame (left) + +JL = { + 'L': (np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]), + np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443])), + 'R': (np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]), + np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443])), +} + + +def tool_of(side): + t = TOOL.copy() + if side == 'R': + t[1] = -t[1] + return t + + +def fk(q, side, tool=None): + """Tool position, wrist-yaw rotation, and joint (pos, axis) list in the FK frame.""" + tool = tool_of(side) if tool is None else tool + p = _TORSO.copy() + R = np.eye(3) + joints = [] + for (xyz, R0, ax), qi in zip(CHAINS[side], q): + p = p + R @ np.array(xyz) + R = R @ R0 + joints.append((p.copy(), R @ _AXV[ax])) + R = R @ _AX[ax](qi) + return p + R @ tool, R, joints + + +def jacobian(q, side, tool=None): + pt, R, joints = fk(q, side, tool) + J = np.zeros((3, 7)) + for i, (pj, a) in enumerate(joints): + J[:, i] = np.cross(a, pt - pj) + return pt, R, J + + +Q_REST = np.array([0.0, 0.1, 0.0, 0.3, 0.0, 0.0, 0.0]) + + +def ik(target, q0, side, n_iter=40, active=(0, 1, 2, 3), q_rest=None, w_rest=3e-4, tool=None): + """Position IK: min |p(q) - target|^2 + w_rest |q - q_rest|^2 (Levenberg-Marquardt).""" + q = np.array(q0, dtype=float).copy() + lo, hi = JL[side] + act = list(active) + if q_rest is None: + q_rest = Q_REST.copy() + if side == 'R': + q_rest[[1, 2, 4, 6]] *= -1 + q_rest = np.asarray(q_rest, dtype=float) + lam = 1e-4 + for _ in range(n_iter): + p, _, J = jacobian(q, side, tool) + e = target - p + Ja = J[:, act] + A = Ja.T @ Ja + (lam + w_rest) * np.eye(len(act)) + b = Ja.T @ e + w_rest * (q_rest[act] - q[act]) + dq = np.linalg.solve(A, b) + n = np.linalg.norm(dq) + if n > 0.2: + dq *= 0.2 / n + q[act] = np.clip(q[act] + dq, lo[act] + 0.02, hi[act] - 0.02) + if n < 1e-5: + break + p, _, _ = fk(q, side, tool) + return q, float(np.linalg.norm(target - p)) diff --git a/policies/reach_target_dual/opus-s2/g1reach_vision.py b/policies/reach_target_dual/opus-s2/g1reach_vision.py new file mode 100644 index 0000000000000000000000000000000000000000..75c57e4ce7d116d20a5471423cbe6ca60dc0c19e --- /dev/null +++ b/policies/reach_target_dual/opus-s2/g1reach_vision.py @@ -0,0 +1,86 @@ +"""Colour segmentation of the target spheres and their floor shadows.""" + +import numpy as np +import cv2 + + +def sphere_mask(img, color): + im = img.astype(np.int16) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + if color == 'red': + return (r > 25) & (r > g + 20) & (r > b + 20) + return (g > 25) & (g > r + 20) & (g > b + 20) + + +def circle_fit(xs, ys): + A = np.stack([xs, ys, np.ones_like(xs)], 1) + bb = xs * xs + ys * ys + sol, *_ = np.linalg.lstsq(A, bb, rcond=None) + cx, cy = sol[0] / 2, sol[1] / 2 + r = np.sqrt(max(sol[2] + cx * cx + cy * cy, 0.0)) + return cx, cy, r + + +def find_sphere(img, color): + """Largest blob of the colour: dict(u, v, r, area, lit, border) or None.""" + m = sphere_mask(img, color).astype(np.uint8) + n, lab, stats, cents = cv2.connectedComponentsWithStats(m, connectivity=8) + if n <= 1: + return None + k = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + area = int(stats[k, cv2.CC_STAT_AREA]) + if area < 3: + return None + blob = (lab == k).astype(np.uint8) + ch = 0 if color == 'red' else 1 + vals = img[..., ch][blob > 0] + lit = float(np.percentile(vals, 90)) >= 235 + # boundary pixels not on the image border and next to background (not to an + # occluding robot part) + er = cv2.erode(blob, np.ones((3, 3), np.uint8)) + edge = (blob > 0) & (er == 0) + H, W = blob.shape + ys, xs = np.nonzero(edge) + keep = (xs > 0) & (xs < W - 1) & (ys > 0) & (ys < H - 1) + border = bool((~keep).any()) + im = img.astype(np.int16) + bg = ((im[..., 2] > im[..., 0] + 15) & (im[..., 2] >= im[..., 1])).astype(np.uint8) + near_bg = cv2.dilate(bg, np.ones((3, 3), np.uint8)) > 0 + keep2 = keep & near_bg[ys, xs] + if keep2.sum() >= 8: + keep = keep2 + xs, ys = xs[keep] + 0.5, ys[keep] + 0.5 + if len(xs) >= 6: + u, v, r = circle_fit(xs.astype(float), ys.astype(float)) + r += 0.5 + else: + u, v = cents[k][0] + 0.5, cents[k][1] + 0.5 + r = np.sqrt(area / np.pi) + r_area = np.sqrt(area / np.pi) + if not border and (r > 1.3 * r_area or r < 0.8 * r_area): + u, v = cents[k][0] + 0.5, cents[k][1] + 0.5 + r = r_area + return dict(u=float(u), v=float(v), r=float(r), area=area, lit=lit, border=border, + cu=float(cents[k][0] + 0.5), cv=float(cents[k][1] + 0.5)) + + +def shadow_mask(img): + im = img.astype(np.int16) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + return (b < 126) & (b > r + 30) & (g < 100) & (g > r + 15) + + +def find_shadows(img, min_area=8, v_min=28): + """Dark blobs on the near floor: list of dict(u, v, area, w, h).""" + m = shadow_mask(img).astype(np.uint8) + m[:v_min] = 0 + m = cv2.morphologyEx(m, cv2.MORPH_OPEN, np.ones((2, 2), np.uint8)) + n, lab, stats, cents = cv2.connectedComponentsWithStats(m, connectivity=4) + out = [] + for k in range(1, n): + a = int(stats[k, cv2.CC_STAT_AREA]) + if a < min_area: + continue + out.append(dict(u=float(cents[k][0] + 0.5), v=float(cents[k][1] + 0.5), area=a, + w=int(stats[k, cv2.CC_STAT_WIDTH]), h=int(stats[k, cv2.CC_STAT_HEIGHT]))) + return out diff --git a/policies/reach_target_dual/opus-s2/policy.py b/policies/reach_target_dual/opus-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..cdb9894608706b07be7c83292a086d782955cf84 --- /dev/null +++ b/policies/reach_target_dual/opus-s2/policy.py @@ -0,0 +1,338 @@ +"""Dual reach: touch the red sphere with the left hand and the green one with the right. + +Hand-written pipeline: + 1. Stand still for a few steps and locate both spheres with the head camera: the + sphere disc gives a viewing ray, its floor shadow (light from straight above) + gives the horizontal position; together they give the 3D centre (world frame). + 2. Walk so that the spheres sit at a comfortable reach in front of the shoulders, + then look again from there. + 3. Move each hand (position IK) to the estimate. Once the sphere shows up in the + wrist camera, servo the hand so the sphere sits at a fixed place in that view. + 4. A sphere lights up while it is touched. A hand whose sphere is neither lit nor + seen by its wrist camera searches small offsets around the estimate. +""" + +import numpy as np + +import g1reach_geom as geom +from g1reach_vision import find_sphere, find_shadows + +Q_DEFAULT = np.array([0.018, 0.0, 0.0, 0.028, 0.0, 0.038, 0.0]) +OBS_STEPS = 10 +X_REACH = 0.30 # desired sphere x in the arm frame after walking +WALK_TOL = 0.02 +MOVE_STEPS = 40 +SETTLE = 20 +PROBE_STEPS = 12 +TARGET_BIAS = np.array([0.01, 0.01, 0.035]) # (x, outward, z) on the head estimate +DEFAULT_Z = 0.115 # sphere height (arm frame) when it is not seen in the head view +WR_TARGET = (42.0, 38.0, 56.0) # where the touched sphere sits in the wrist view +PRESS = 0.01 # extra push along the wrist view axis on first contact +OFF_RATE = 0.004 # m per step at which search offsets are approached +MAX_DEV = 0.10 +# typical sphere centres in the arm frame at the start pose (fallback only) +TYPICAL = {'red': np.array([0.46, 0.17, 0.10]), 'green': np.array([0.47, -0.20, 0.08])} # servo may move the hand target this far from the head estimate +SERVO_GAIN = 0.35 +SERVO_STEP = 0.02 +DEBUG = False + + +def _search_offsets(): + # the wrist camera looks down and forward: going up first brings a sphere that is + # higher than estimated into view; y is outward for either hand + offs = [(0, 0, 0), (0, 0, 0.03), (-0.01, 0, 0.06), (-0.02, 0, 0.09), (0.02, 0, -0.02), + (0.03, 0, -0.05), (-0.01, 0.03, 0.04), (-0.01, -0.03, 0.04), (0.03, 0, 0.02), + (-0.02, 0.04, 0.08), (-0.02, -0.04, 0.08), (0.02, 0.03, -0.03), (0.02, -0.03, -0.03), + (-0.03, 0, 0.12), (0.04, 0, -0.08)] + return [np.array(o, dtype=float) for o in offs] + + +SEARCH = _search_offsets() +SIDES = (('L', 'red'), ('R', 'green')) + + +def _rz2(yaw): + c, s = np.cos(yaw), np.sin(yaw) + return np.array([[c, -s], [s, c]]) + + +def _rz3(yaw): + c, s = np.cos(yaw), np.sin(yaw) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1.0]]) + + +def lit_in(img, color): + im = img.astype(np.int16) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + if color == 'red': + m = (r >= 235) & (g < 90) & (b < 90) + else: + m = (g >= 235) & (r < 120) & (b < 120) + return int(m.sum()) + + +def _wrap(a): + return (a + np.pi) % (2 * np.pi) - np.pi + + +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.float32) + self.t = 0 + self.phase = 'observe' + self.phase_t = 0 + self.samples = {'red': [], 'green': []} + self.shadow_only = {'red': [], 'green': []} + self.world = {} + self.quality = {} + self.q_cmd = {'L': Q_DEFAULT.copy(), 'R': Q_DEFAULT.copy()} + self.q_out = {'L': Q_DEFAULT.copy(), 'R': Q_DEFAULT.copy()} + self.integ = {'L': np.zeros(7), 'R': np.zeros(7)} + self.hand = {} + self.yaw0 = float(obs['low_dim_obs'][21]) + self.debug = [] + + # ------------------------------------------------------------ geometry + def _to_world(self, p_fk, pel, yaw): + wxy = pel[:2] + _rz2(yaw) @ p_fk[:2] + return np.array([wxy[0], wxy[1], p_fk[2] - (pel[2] - 0.746)]) + + def _to_fk(self, w, pel, yaw): + xy = _rz2(yaw).T @ (w[:2] - pel[:2]) + return np.array([xy[0], xy[1], w[2] + (pel[2] - 0.746)]) + + def _estimate(self, img, pel, yaw): + cam_h = pel[2] + geom.CAM_H_ABOVE_PELVIS + shadows = [s for s in find_shadows(img) if s['area'] <= 90 and max(s['w'], s['h']) <= 12] + for s in shadows: + s['fp'] = geom.floor_point(s['u'], s['v'], cam_h) + shadows = [s for s in shadows if s['fp'] is not None] + used = set() + for color in ('red', 'green'): + sp = find_sphere(img, color) + if sp is None or sp['area'] < 6: + continue + d = geom.pixel_ray(sp['u'], sp['v']) + best = None + for i, s in enumerate(shadows): + S = s['fp'] + t = (S[:2] @ d[:2]) / (d[:2] @ d[:2]) + if t <= 0: + continue + err = np.linalg.norm(t * d[:2] - S[:2]) + # height from the ray elevation at the shadow's horizontal distance + z_rel = np.linalg.norm(S[:2]) * d[2] / np.linalg.norm(d[:2]) + P = np.array([S[0], S[1], z_rel]) + z_world = cam_h + P[2] + if not (0.5 < z_world < 1.3): + continue + if best is None or err < best[0]: + best = (err, P, i) + if best is None or best[0] > (0.07 if sp['border'] else 0.045): + continue + used.add(best[2]) + self.samples[color].append(self._to_world(geom.CAM_FK + best[1], pel, yaw)) + # shadows that belong to no visible sphere: candidates for a sphere out of view + rest = [s for i, s in enumerate(shadows) + if i not in used and 12 <= s['area'] <= 60 + and 0.18 < s['fp'][0] < 0.6 and abs(s['fp'][1]) < 0.45] + if rest: + ys = [s['fp'][1] for s in rest] + for color, pick in (('red', int(np.argmax(ys))), ('green', int(np.argmin(ys)))): + s = rest[pick] + P = s['fp'].copy() + fk = geom.CAM_FK + P + fk[2] = self._hidden_height(P, cam_h) + self.shadow_only[color].append(self._to_world(fk, pel, yaw)) + + @staticmethod + def _hidden_height(P, cam_h): + """Arm-frame height guess for a sphere whose shadow is seen but the sphere is not.""" + for z_fk in np.arange(-0.05, 0.35, 0.01): + p = np.array([P[0], P[1], z_fk - geom.CAM_FK[2]]) + uv = geom.project(p) + if uv is None: + break + if 0 <= uv[0] < 84 and uv[1] < -4: + return min(z_fk + 0.03, 0.25) + return DEFAULT_Z + + def _fuse(self, prior=None): + for c in ('red', 'green'): + est, qual = None, None + if len(self.samples[c]) >= 2: + est, qual = np.median(np.array(self.samples[c]), axis=0), 'full' + elif prior is None or c not in prior or self.quality.get(c) == 'guess': + if len(self.shadow_only[c]) >= 2: + est, qual = np.median(np.array(self.shadow_only[c]), axis=0), 'shadow' + if prior is not None and c in prior: + keep_prior = est is None or (np.linalg.norm(est - prior[c]) > 0.08 + and self.quality.get(c) == 'full') + if keep_prior: + est, qual = prior[c], self.quality.get(c) + if est is not None: + self.world[c] = est + self.quality[c] = qual + # a shadow-only guess must not duplicate the other sphere + if 'red' in self.world and 'green' in self.world: + if np.linalg.norm(self.world['red'][:2] - self.world['green'][:2]) < 0.08: + for c in ('red', 'green'): + if len(self.samples[c]) < 2 and (prior is None or c not in prior): + del self.world[c] + self.samples = {'red': [], 'green': []} + # nothing seen at all: fall back to the typical placement + for c in ('red', 'green'): + if c not in self.world: + self.world[c] = self._to_world(TYPICAL[c], self.pel_now, self.yaw_now) + self.quality[c] = 'guess' + self.shadow_only = {'red': [], 'green': []} + + def _walk_goal(self): + pts = [self.world[c][:2] for c in ('red', 'green') if c in self.world] + if len(pts) < 2: + return None + m = np.mean(pts, axis=0) + return m - _rz2(self.yaw0) @ np.array([X_REACH, 0.0]) + + # ------------------------------------------------------------ control + def _arm_out(self, raw): + raw[4:11] = self.q_out['L'] + raw[11:18] = self.q_out['R'] + + def act(self, obs, tools): + raw = self.hold.copy() + lo = obs['low_dim_obs'] + pel, yaw = lo[18:21].astype(float), float(lo[21]) + self.pel_now, self.yaw_now = pel, yaw + t = self.t + self.t += 1 + self.phase_t += 1 + pt = self.phase_t + + if self.phase == 'observe': + if pt >= 3: + self._estimate(tools.image('head'), pel, yaw) + if pt >= OBS_STEPS: + self._fuse() + self.goal = self._walk_goal() + self.phase, self.phase_t = ('walk' if self.goal is not None else 'settle'), 0 + self._arm_out(raw) + return raw + + if self.phase == 'walk': + e_b = _rz2(yaw).T @ (self.goal - pel[:2]) + v = np.clip(1.5 * e_b, -0.3, 0.3) + if np.linalg.norm(e_b) < WALK_TOL or pt > 250: + self.phase, self.phase_t = 'settle', 0 + v = np.zeros(2) + else: + sp = np.linalg.norm(v) + if sp < 0.07: + v = v / max(sp, 1e-6) * 0.07 + raw[0], raw[1] = v[0], v[1] + raw[3] = np.clip(-1.5 * _wrap(yaw - self.yaw0), -0.3, 0.3) + self._arm_out(raw) + return raw + + if self.phase == 'settle': + if pt >= 25: + self._estimate(tools.image('head'), pel, yaw) + if pt >= 35: + self._fuse(prior=dict(self.world)) + self.phase, self.phase_t = 'reach', 0 + self._arm_out(raw) + return raw + + # ---- reach / servo / search + if not self.hand: + for side, c in SIDES: + if c not in self.world: + continue + b = TARGET_BIAS * np.array([1, 1 if side == 'L' else -1, 1]) + tgt0 = self.world[c] + _rz3(yaw) @ b + self.hand[side] = dict(color=c, k=0, lit=False, unlit=0, seen=-100, wr=None, + tgt=tgt0.copy(), tgt0=tgt0, pressed=False, off=np.zeros(3)) + imgs = None + if pt % 2 == 0: + imgs = {cam: tools.image(cam) for cam in ('head', 'left_wrist', 'right_wrist')} + for side, c in SIDES: + if side not in self.hand: + continue + h = self.hand[side] + qm = (lo[0:7] if side == 'L' else lo[9:16]).astype(float) + if imgs is not None: + lit = sum(lit_in(im, c) for im in imgs.values()) >= 3 + h['lit'] = lit + h['unlit'] = 0 if lit else h['unlit'] + 2 + if pt > MOVE_STEPS // 2: + wimg = imgs['left_wrist' if side == 'L' else 'right_wrist'] + s = find_sphere(wimg, c) + h['wr'] = None if s is None else (round(s['u'], 1), round(s['v'], 1), round(s['r'], 1), s['area']) + ok = s is not None and s['r'] < 75 and ( + s['area'] >= 60 or (s['border'] and s['area'] >= 20)) + if ok: + h['seen'] = pt + if not lit: + if s['border'] and s['area'] < 400: + # a sliver at the edge: only its direction is reliable + p_s = geom.wrist_sphere_cam(s['cu'], s['cv'], 40.0) + else: + u = float(np.clip(s['u'], -30, 114)) + v = float(np.clip(s['v'], -30, 114)) + p_s = geom.wrist_sphere_cam(u, v, float(np.clip(s['r'], 20.0, 60.0))) + p_t = geom.wrist_sphere_cam(*WR_TARGET) + _, R_link, _ = geom.fk(qm, side) + e = _rz3(yaw) @ (R_link @ geom.R_LC @ (p_s - p_t)) + step = SERVO_GAIN * e + n = np.linalg.norm(step) + if n > SERVO_STEP: + step *= SERVO_STEP / n + new = h['tgt'] + step + dev = new - h['tgt0'] + nd = np.linalg.norm(dev) + if nd > MAX_DEV: + new = h['tgt0'] + dev * MAX_DEV / nd + h['tgt'] = new + if imgs is not None: + if h['lit'] and not h['pressed']: + # first contact: lean a little further in along the wrist view axis + _, R_link, _ = geom.fk(qm, side) + axis = _rz3(yaw) @ (R_link @ geom.R_LC @ np.array([1.0, 0, 0])) + h['tgt'] = h['tgt'] + PRESS * axis + h['pressed'] = True + elif h['unlit'] >= 20: + h['pressed'] = False + recently_seen = pt - h['seen'] < 30 + if pt > MOVE_STEPS + SETTLE and h['unlit'] >= PROBE_STEPS and not recently_seen: + h['k'] = (h['k'] + 1) % len(SEARCH) + h['unlit'] = 0 + goal = SEARCH[h['k']].copy() + if side == 'R': + goal[1] = -goal[1] + d_off = goal - h['off'] + n = np.linalg.norm(d_off) + h['off'] = goal if n <= OFF_RATE else h['off'] + d_off * OFF_RATE / n + tgt = self._to_fk(h['tgt'], pel, yaw) + h['off'] + q, err = geom.ik(tgt, self.q_cmd[side], side, n_iter=60 if pt <= 1 else 20) + self.q_cmd[side] = q + if pt < MOVE_STEPS: + a = (pt + 1) / MOVE_STEPS + self.q_out[side] = Q_DEFAULT + a * (q - Q_DEFAULT) + else: + ig = self.integ[side] + ig[:4] = np.clip(ig[:4] + 0.05 * (q[:4] - qm[:4]), -0.3, 0.3) + self.q_out[side] = q + ig + self._arm_out(raw) + if DEBUG: + rel = {} + for side, c in SIDES: + if side in self.hand: + qm = lo[0:7] if side == 'L' else lo[9:16] + rel[side] = (geom.fk(qm, side)[0] - self._to_fk(self.world[c], pel, yaw)).round(4).tolist() + self.debug.append(dict(t=t, phase=self.phase, lit={s: self.hand[s]['lit'] for s in self.hand}, + k={s: self.hand[s]['k'] for s in self.hand}, rel=rel, + tgt={s: self.hand[s]['tgt'].round(4).tolist() for s in self.hand}, + wr={s: self.hand[s]['wr'] for s in self.hand})) + return raw diff --git a/policies/reach_target_dual/opus-s3/episodes.csv b/policies/reach_target_dual/opus-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..0a2d4d998f23c8828283a24ab738b99faea38dbb --- /dev/null +++ b/policies/reach_target_dual/opus-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,700,timeout,0 +620001,1,575,success,0 +620002,0,700,timeout,0 +620003,1,651,success,0 +620004,1,424,success,0 +620005,1,390,success,0 +620006,1,393,success,0 +620007,1,429,success,0 +620008,0,700,timeout,0 +620009,0,700,timeout,0 +620010,1,378,success,0 +620011,0,700,timeout,0 +620012,0,700,timeout,0 +620013,0,700,timeout,0 +620014,1,644,success,0 +620015,0,700,timeout,0 +620016,1,519,success,0 +620017,1,366,success,0 +620018,1,552,success,0 +620019,1,598,success,0 +620020,1,410,success,0 +620021,1,401,success,0 +620022,1,425,success,0 +620023,0,700,timeout,0 +620024,0,700,timeout,0 +620025,1,375,success,0 +620026,1,662,success,0 +620027,1,416,success,0 +620028,0,700,timeout,0 +620029,0,700,timeout,0 +620030,0,700,timeout,0 +620031,1,544,success,0 +620032,1,465,success,0 +620033,1,599,success,0 +620034,1,438,success,0 +620035,1,621,success,0 +620036,0,700,timeout,0 +620037,1,396,success,0 +620038,1,384,success,0 +620039,1,637,success,0 +620040,1,648,success,0 +620041,1,469,success,0 +620042,1,453,success,0 +620043,1,451,success,0 +620044,1,560,success,0 +620045,1,628,success,0 +620046,0,700,timeout,0 +620047,1,390,success,0 +620048,1,343,success,0 +620049,1,341,success,0 +620050,0,700,timeout,0 +620051,1,396,success,0 +620052,0,700,timeout,0 +620053,1,434,success,0 +620054,1,590,success,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,0,700,timeout,0 +620058,0,700,timeout,0 +620059,1,386,success,0 +620060,1,359,success,0 +620061,1,458,success,0 +620062,1,366,success,0 +620063,1,519,success,0 +620064,0,700,timeout,0 +620065,0,700,timeout,0 +620066,1,420,success,0 +620067,1,304,success,0 +620068,1,424,success,0 +620069,0,700,timeout,0 +620070,1,380,success,0 +620071,1,553,success,0 +620072,0,700,timeout,0 +620073,1,392,success,0 +620074,0,700,timeout,0 +620075,1,557,success,0 +620076,1,423,success,0 +620077,0,700,timeout,0 +620078,0,700,timeout,0 +620079,1,347,success,0 +620080,1,448,success,0 +620081,1,436,success,0 +620082,1,439,success,0 +620083,1,577,success,0 +620084,1,521,success,0 +620085,1,402,success,0 +620086,0,700,timeout,0 +620087,1,578,success,0 +620088,1,389,success,0 +620089,0,700,timeout,0 +620090,1,506,success,0 +620091,0,700,timeout,0 +620092,1,368,success,0 +620093,0,700,timeout,0 +620094,1,405,success,0 +620095,0,700,timeout,0 +620096,1,446,success,0 +620097,0,700,timeout,0 +620098,0,700,timeout,0 +620099,1,417,success,0 diff --git a/policies/reach_target_dual/opus-s3/policy.py b/policies/reach_target_dual/opus-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..6ae4213386c8ad5906b48638956bcc59ea2819e2 --- /dev/null +++ b/policies/reach_target_dual/opus-s3/policy.py @@ -0,0 +1,586 @@ +"""Touch the red sphere with the left hand and the green sphere with the right hand. + +Hand-written control: + 1. lower the forearms out of the way, stand tall and locate both spheres in the head + camera (colour blobs, circle fit; distance from the apparent radius); turn towards + a sphere that is out of view; + 2. walk (at normal height) to a spot from which both are within comfortable reach, + squat if a sphere is low, and measure again; + 3. per arm, sweep the hand point through the sphere along a line near the head-camera + ray (inverse kinematics on a kinematic G1 arm model; head-camera pose and focal + length calibrated offline by matching that arm model to the arm silhouette), while + tracking the sphere in the head image; retry with small sideways offsets; + 4. a touched sphere turns saturated in the camera images: keep sweeping slowly over the + touching stretch, then hold the hand in its middle. +""" + +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]]) + + +_ROT = (_ry, _rx, _rz, _ry, _rx, _ry, _rz) +_TORSO = np.array([-0.0039635, 0, 0.044]) + + +def _joints(s): + return [(np.array([0.0039563, s * 0.10022, 0.23778]), _rx(s * 0.27931)), + (np.array([0, s * 0.038, -0.013831]), _rx(-s * 0.27925)), + (np.array([0, s * 0.00624, -0.1032]), np.eye(3)), + (np.array([0.015783, 0, -0.080518]), np.eye(3)), + (np.array([0.100, s * 0.00188791, -0.010]), np.eye(3)), + (np.array([0.038, 0, 0]), np.eye(3)), + (np.array([0.046, 0, 0]), np.eye(3))] + + +JOINTS = {'L': _joints(1), 'R': _joints(-1)} + + +def fk(q, side): + """Wrist-yaw link position and rotation in the (upright) pelvis frame.""" + p = _TORSO.copy() + R = np.eye(3) + for (o, r0), rot, qi in zip(JOINTS[side], _ROT, q): + p = p + R @ o + R = R @ r0 @ rot(qi) + return p, R + + +SHOULDER = {s: _TORSO + JOINTS[s][0][0] for s in 'LR'} + +# ----------------------------------------------------------------------------- head camera +HEAD_P = np.array([0.00983771634691396, -0.00012230200000887953, 0.4386567502905857]) +HEAD_R = np.array([[0.5742387294861857, 0.015630101774682336, 0.8185386866096216], + [0.001861066585896575, 0.9997902327422175, -0.020396738573250955], + [-0.818685787093714, 0.013235952242878341, 0.5740891843424419]]) +HEAD_F = 80.58299288401194 +C0 = 41.5 +SPHERE_R = 0.06 + + +def head_ray(u, v): + ray = np.array([HEAD_F, -(u - C0), -(v - C0)]) + return HEAD_R @ (ray / np.linalg.norm(ray)) + + +# ----------------------------------------------------------------------------- vision + + +def color_masks(img): + hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) + h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2] + sat = (s > 150) & (v > 20) + red = sat & ((h < 10) | (h >= 170)) + grn = sat & (h >= 45) & (h < 80) + return red, grn + + +def lit_masks(img): + im = img.astype(int) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + red = (r >= 235) & (g < 90) & (b < 90) + grn = (g >= 235) & (r < 90) & (b < 90) + return red, grn + + +def fit_circle(pts): + x, y = pts[:, 0], pts[:, 1] + A = np.stack([x, y, np.ones_like(x)], 1) + sol = np.linalg.lstsq(A, x * x + y * y, rcond=None)[0] + cx, cy = sol[0] / 2, sol[1] / 2 + return cx, cy, np.sqrt(max(sol[2] + cx * cx + cy * cy, 1e-6)) + + +def detect(mask, min_area=6): + m = mask.astype(np.uint8) + n, lab, stats, cent = cv2.connectedComponentsWithStats(m, connectivity=8) + if n <= 1: + return None + k = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + area = int(stats[k, cv2.CC_STAT_AREA]) + if area < min_area: + return None + blob = (lab == k).astype(np.uint8) + cs, _ = cv2.findContours(blob, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) + pts = np.concatenate([c[:, 0, :] for c in cs], 0).astype(float) + H, W = mask.shape + keep = (pts[:, 0] > 0) & (pts[:, 0] < W - 1) & (pts[:, 1] > 0) & (pts[:, 1] < H - 1) + pts = pts[keep] + if len(pts) < 6: + return None + for _ in range(4): + cx, cy, r = fit_circle(pts) + d = np.hypot(pts[:, 0] - cx, pts[:, 1] - cy) + good = d > r - 1.0 + if good.sum() < 6 or good.all(): + break + pts = pts[good] + cx, cy, r = fit_circle(pts) + return np.array([cx, cy, r + 0.5, area]) + + +def occluder_mask(img): + hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) + m = (hsv[..., 1] < 70) | (hsv[..., 2] < 45) + return cv2.dilate(m.astype(np.uint8), np.ones((5, 5), np.uint8)) > 0 + + +def detect_track(mask, occ, ref): + """Sphere centre given a reference (cx, cy, r): fit the fixed-radius circle to the + blob boundary that borders the background (not the arm or the image edge).""" + m = mask.astype(np.uint8) + n, lab, stats, cent = cv2.connectedComponentsWithStats(m, connectivity=8) + if n <= 1: + return None + # the blob closest to the reference centre + d2 = (cent[1:, 0] - ref[0]) ** 2 + (cent[1:, 1] - ref[1]) ** 2 + k = 1 + int(np.argmin(d2)) + if stats[k, cv2.CC_STAT_AREA] < 8: + return None + blob = (lab == k).astype(np.uint8) + cs, _ = cv2.findContours(blob, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) + pts = np.concatenate([c[:, 0, :] for c in cs], 0) + H, W = mask.shape + keep = (pts[:, 0] > 0) & (pts[:, 0] < W - 1) & (pts[:, 1] > 0) & (pts[:, 1] < H - 1) + keep &= ~occ[pts[:, 1], pts[:, 0]] + pts = pts[keep].astype(float) + 0.0 + if len(pts) < 10: + return None + # boundary must span a reasonable arc + ang = np.arctan2(pts[:, 1] - ref[1], pts[:, 0] - ref[0]) + span = np.histogram(ang, bins=8, range=(-np.pi, np.pi))[0] + if (span > 0).sum() < 3: + return None + r = ref[2] - 0.5 + c = np.array([ref[0], ref[1]], float) + for _ in range(10): + dv = pts - c + dist = np.linalg.norm(dv, axis=1) + 1e-9 + J = -dv / dist[:, None] + res = dist - r + w = 1.0 / np.maximum(1.0, np.abs(res)) + step = np.linalg.lstsq(J * w[:, None], -res * w, rcond=None)[0] + c = c + step + if np.linalg.norm(step) < 0.01: + break + res = np.abs(np.linalg.norm(pts - c, axis=1) - r) + if np.median(res) > 1.0: + return None + return np.array([c[0], c[1], ref[2], len(pts)]) + + +# ----------------------------------------------------------------------------- IK +LO = np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.972, -1.614, -1.614]) +HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.972, 1.614, 1.614]) +MIRROR = np.array([1, -1, -1, 1, -1, 1, -1]) +Q_NOM = np.array([-0.8, 0.2, 0.0, 0.6, 0.0, 0.0, 0.0]) +TIP = 0.15 # hand point: along the gripper, from the wrist-yaw joint + + +def to_side(q, side): + return q * MIRROR if side == 'R' else q + + +def lo_hi(side): + if side == 'L': + return LO, HI + a, b = LO * MIRROR, HI * MIRROR + return np.minimum(a, b), np.maximum(a, b) + + +def hand_point(q, side, tip=TIP): + p, R = fk(q, side) + return p + R[:, 0] * tip, R + + +def ik(target, side, q0, tip=TIP): + """Joint angles putting the hand point at target, gripper pointing away from the shoulder.""" + lo, hi = lo_hi(side) + nom = to_side(Q_NOM, side) + d = target - SHOULDER[side] + d = d / np.linalg.norm(d) + + def res(q): + h, R = hand_point(q, side, tip) + return np.concatenate([(h - target) * 10.0, (R[:, 0] - d) * 0.5, (q - nom) * 0.05]) + + x0 = np.clip(q0, lo + 1e-4, hi - 1e-4) + r = least_squares(res, x0, bounds=(lo, hi), xtol=1e-6, max_nfev=200) + return r.x, np.linalg.norm(hand_point(r.x, side, tip)[0] - target) + + +# ----------------------------------------------------------------------------- policy +HIGH = 0.9 # stand tall to see the spheres +WALK_HEIGHT = 0.74 # the controller only steps at normal height +SIDES = ('L', 'R') +COLOR_OF = {'L': 0, 'R': 1} # 0 red (left hand), 1 green (right hand) +Q_DOWN = np.array([0.0, 0.15, 0.0, 1.3, 0.0, 0.0, 0.0]) # forearms down, out of the view +REACH_D = 0.42 # desired shoulder-to-sphere distance after walking +DZ_MAX = 0.30 # at most this far from shoulder height down to the lower sphere +TIP_T = 0.16 # hand point that should reach the sphere centre +SWEEP = (-0.08, 0.10) +SWEEP_STEPS = 110 +LAG_OK = 0.03 # hand-to-target distance under which the sweep advances +STALL_MAX = 15 +HOLD_LOST = 20 # unlit steps at the hold spot before sweeping on +KI = 0.02 # integral gain (per step) on arm joint tracking error +I_MAX = 0.12 +RETREAT_STEPS = 25 +OFFSETS = [(0.0, 0.0), (0.0, 0.035), (0.035, 0.0), (0.0, -0.035), (-0.035, 0.0), + (0.035, 0.035), (-0.035, 0.035), (0.035, -0.035), (-0.035, -0.035)] +T_DOWN, T_MEAS0, T_MEAS1 = 25, 60, 72 + + +def pelvis(o): + return o[18:21].astype(float), float(o[21]) + + +def to_world(p_local, o): + pos, yaw = pelvis(o) + return pos + _rz(yaw) @ p_local + + +def to_local(p_world, o): + pos, yaw = pelvis(o) + return _rz(yaw).T @ (p_world - pos) + + +LO2 = np.array([-2.5, 0.0, -1.0, -0.6, -1.0, -1.2, -1.0]) # comfortable joint ranges +HI2 = np.array([0.8, 1.6, 1.0, 1.9, 1.0, 1.2, 1.0]) +Q_SEEDS = [np.array([-0.8, 0.2, 0.0, 0.6, 0.0, 0.0, 0.0]), + np.array([-0.4, 0.1, 0.0, 1.2, 0.0, 0.3, 0.0]), + np.array([-1.0, 0.3, 0.0, 0.2, 0.0, 0.5, 0.0])] + + +def lo_hi2(side): + if side == 'L': + return LO2, HI2 + a, b = LO2 * MIRROR, HI2 * MIRROR + return np.minimum(a, b), np.maximum(a, b) + + +def ik_dir(target, side, q0, d, tip=TIP_T, wdir=0.3): + lo, hi = lo_hi2(side) + nom = to_side(Q_NOM, side) + + def res(q): + h, R = hand_point(q, side, tip) + return np.concatenate([(h - target) * 10.0, (R[:, 0] - d) * wdir, (q - nom) * 0.05]) + + r = least_squares(res, np.clip(q0, lo + 1e-4, hi - 1e-4), bounds=(lo, hi), max_nfev=60) + h, _ = hand_point(r.x, side, tip) + if np.linalg.norm(h - target) < 0.005 and np.all(r.x > lo + 0.02) and np.all(r.x < hi - 0.02): + return r.x + best = (r.cost, r.x) + for qs in [to_side(q, side) for q in Q_SEEDS]: + r = least_squares(res, np.clip(qs, lo + 1e-4, hi - 1e-4), bounds=(lo, hi), max_nfev=60) + # prefer staying on the current branch unless another start is clearly better + cost = r.cost * 1.5 + 1e-3 + if best is None or cost < best[0]: + best = (cost, r.x) + return best[1] + + +def plausible(p_local, s): + x, y, z = p_local + if not (0.15 < x < 0.9 and abs(y) < 0.6 and -0.6 < z < 0.4): + return False + return y > -0.15 if s == 'L' else y < 0.15 + + +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.t = 0 + self.q_cmd = {'L': np.zeros(7), 'R': np.zeros(7)} + self.q_ik = {} + self.integ = {'L': np.zeros(7), 'R': np.zeros(7)} + self.reach_h = WALK_HEIGHT + self.hist = [] + self.meas = {'L': [], 'R': []} + self.sph = {} # world sphere estimate + self.raydir = {} # world direction of the measuring head ray + self.phase = 'down' + self.t_phase = 0 + self.arm = {s: dict(state='sweep', k=0, attempt=0) for s in SIDES} + self.log = [] + + # -------------------------------------------------------------- perception + def observe(self, tools): + head = tools.image('head') + red, grn = color_masks(head) + dets = [detect(red), detect(grn)] + nlit = [0, 0] + ncol = [0, 0] + for cam in ('head', 'left_wrist', 'right_wrist'): + img = head if cam == 'head' else tools.image(cam) + lr, lg = lit_masks(img) + cr, cg = (red, grn) if cam == 'head' else color_masks(img) + nlit[0] += int(lr.sum()) + nlit[1] += int(lg.sum()) + ncol[0] += int(cr.sum()) + ncol[1] += int(cg.sum()) + # True: lit, False: seen and not lit, None: not visible enough to tell + lit = [True if nlit[i] >= 3 else (False if ncol[i] >= 25 else None) for i in range(2)] + self.head = head + return dets, lit + + def collect(self, dets, o): + for s in SIDES: + d = dets[COLOR_OF[s]] + if d is None or not (3.0 < d[2] < 16.0): + continue + # fraction of the fitted disc that lies inside the image + yy, xx = np.mgrid[0:84, 0:84] + disc = ((xx - d[0]) ** 2 + (yy - d[1]) ** 2) <= d[2] ** 2 + vis = disc.sum() + if vis < 0.5 * np.pi * d[2] ** 2 or d[3] < 0.6 * vis: + continue + ray = head_ray(d[0], d[1]) + depth = SPHERE_R / np.sin(np.arctan(d[2] / HEAD_F)) + p_local = HEAD_P + ray * depth + if not plausible(p_local, s): + continue + self.meas[s].append((to_world(p_local, o), _rz(pelvis(o)[1]) @ ray, to_world(HEAD_P, o), d[2], + np.concatenate([d[:3], o[18:22]]))) + + def estimate(self): + for s in SIDES: + if not self.meas[s]: + continue + P = np.array([m[0] for m in self.meas[s]]) + D = np.array([m[1] for m in self.meas[s]]) + self.sph[s] = np.median(P, 0) + d = D.mean(0) + self.raydir[s] = d / np.linalg.norm(d) + C = np.array([m[2] for m in self.meas[s]]) + rr = np.array([m[3] for m in self.meas[s]]) + self.log.append(('est', self.t, s, self.sph[s].round(3).tolist(), len(P), + 'cam', np.median(C, 0).round(4).tolist(), 'ray', self.raydir[s].round(4).tolist(), + 'r', round(float(np.median(rr)), 3), + 'raw', np.median(np.array([m[4] for m in self.meas[s]]), 0).round(4).tolist())) + self.meas = {'L': [], 'R': []} + + def walk_goal(self, o): + """Pelvis xy (world) that puts each sphere at a comfortable reach from its shoulder.""" + pos, yaw = pelvis(o) + if not self.sph: + return pos[:2].copy() + xs, ys = [], [] + # squat so that the shoulders are no more than DZ_MAX above the lower sphere + min_z = min(S[2] for S in self.sph.values()) + self.reach_h = float(np.clip(min_z + DZ_MAX - SHOULDER['L'][2] - 0.01, 0.62, WALK_HEIGHT)) + for s, S in self.sph.items(): + sh = SHOULDER[s] + dz = max(self.reach_h + 0.01 + sh[2] - S[2], 0.0) + h = np.sqrt(max(REACH_D ** 2 - dz ** 2, 0.1 ** 2)) + xs.append(S[0] - np.sqrt(max(h ** 2 - 0.05 ** 2, 0.05 ** 2))) + ys.append(S[1] - sh[1] * 0.5) + return np.array([np.mean(xs), np.mean(ys)]) + + def start_tracking(self, o): + """Head-image track (u, v, r) and camera depth of each sphere, from the world estimate.""" + self.pix, self.depth = {}, {} + for s, S in self.sph.items(): + p = to_local(S, o) - HEAD_P + c = HEAD_R.T @ p + u = C0 - HEAD_F * c[1] / c[0] + v = C0 - HEAD_F * c[2] / c[0] + dist = np.linalg.norm(p) + r = HEAD_F * np.tan(np.arcsin(min(SPHERE_R / dist, 0.9))) + self.pix[s] = np.array([u, v, r]) + self.depth[s] = dist + + def track(self, head): + red, grn = color_masks(head) + occ = occluder_mask(head) + for s, m in (('L', red), ('R', grn)): + if s not in self.pix: + continue + det = detect_track(m, occ, self.pix[s]) + if det is None: + continue + gate = 12 if self.t - self.t_phase < 10 else 6 + if np.hypot(det[0] - self.pix[s][0], det[1] - self.pix[s][1]) > gate: + continue + self.pix[s][:2] = 0.7 * self.pix[s][:2] + 0.3 * det[:2] + self.ntrack = getattr(self, 'ntrack', 0) + 1 + + def set_phase(self, p): + self.phase = p + self.t_phase = self.t + + # -------------------------------------------------------------- arms + def sweep_geometry(self, s, attempt): + """Sphere centre (local), sweep direction and offset base point for this attempt.""" + off = OFFSETS[attempt % len(OFFSETS)] + ray = head_ray(self.pix[s][0], self.pix[s][1]) + centre = HEAD_P + ray * self.depth[s] + sh = centre - SHOULDER[s] + d = ray + sh / np.linalg.norm(sh) + d /= np.linalg.norm(d) + lat = np.cross(np.array([0, 0, 1.0]), d) + lat /= np.linalg.norm(lat) + up = np.cross(d, lat) + return centre + lat * off[0] + up * off[1], d + + def reach_step(self, s, lit, o): + """Sweep the hand through the sphere; on touch, find the touching stretch of the + sweep line and hold the hand in its middle.""" + a = self.arm[s] + if s not in self.sph: + return + qa = o[0:7] if s == 'L' else o[9:16] + base, d = self.sweep_geometry(s, a['attempt']) + hand = hand_point(qa, s, TIP_T)[0] + delta_act = float((hand - base) @ d) + k = a['k'] + st = a['state'] + if st == 'sweep' and lit: + a['state'] = st = 'touch' + a['enter'] = delta_act + a['unlit'] = 0 + # continue from where the (lagging) hand actually is + f = (delta_act - SWEEP[0]) / (SWEEP[1] - SWEEP[0]) + a['k'] = int(np.clip(RETREAT_STEPS + f * SWEEP_STEPS, RETREAT_STEPS, RETREAT_STEPS + SWEEP_STEPS - 1)) + hw = to_world(hand, o) + rel = hw - self.sph[s] + self.log.append(('lit', self.t, s, a['attempt'], k, 'rel', rel.round(3).tolist(), + 'along', round(float(rel @ self.raydir[s]), 3), 'dact', round(delta_act, 3))) + if st == 'touch': + # keep sweeping slowly until the touch ends, then go back to its middle + a['unlit'] = a['unlit'] + 1 if lit is False else 0 + end = a['unlit'] >= 3 or a['k'] >= RETREAT_STEPS + SWEEP_STEPS - 1 + if end: + exit_d = delta_act if a['unlit'] >= 3 else SWEEP[1] + a['hold'] = 0.5 * (a['enter'] + exit_d) + a['state'] = st = 'hold' + a['unlit'] = 0 + self.log.append(('hold', self.t, s, round(a['enter'], 3), round(exit_d, 3))) + elif self.t % 2 == 0: + a['k'] += 1 + delta = SWEEP[0] + (a['k'] - RETREAT_STEPS) / SWEEP_STEPS * (SWEEP[1] - SWEEP[0]) + if st == 'hold': + a['unlit'] = a['unlit'] + 1 if lit is False else 0 + if a['unlit'] > HOLD_LOST: + # the hold spot does not touch: resume the sweep past the touch + a['state'] = st = 'sweep' + self.log.append(('lost', self.t, s)) + else: + delta = a['hold'] + if st == 'sweep': + # advance the sweep only while the hand keeps up with its target + lag = np.linalg.norm(hand - a.get('target', np.zeros(3))) + if k < RETREAT_STEPS or lag < LAG_OK or a.get('stall', 0) > STALL_MAX: + a['k'] += 1 + a['stall'] = 0 + else: + a['stall'] = a.get('stall', 0) + 1 + k = a['k'] + if k >= RETREAT_STEPS + SWEEP_STEPS: + a['attempt'] += 1 + a['k'] = k = 0 + base, d = self.sweep_geometry(s, a['attempt']) + frac = 0.0 if k < RETREAT_STEPS else (k - RETREAT_STEPS) / SWEEP_STEPS + delta = SWEEP[0] + frac * (SWEEP[1] - SWEEP[0]) + target = base + d * delta + a['target'] = target + if self.t % 2 == 0 or s not in self.q_ik: + self.q_ik[s] = ik_dir(target, s, self.q_ik.get(s, to_side(Q_NOM, s)), d) + lim = 0.03 if (st == 'sweep' and a['k'] < RETREAT_STEPS) else 0.05 + self.q_cmd[s] = self.q_cmd[s] + np.clip(self.q_ik[s] - self.q_cmd[s], -lim, lim) + + # -------------------------------------------------------------- main + def act(self, obs, tools): + t = self.t + self.t += 1 + o = obs['low_dim_obs'] + raw = self.hold.copy() + raw[2] = WALK_HEIGHT + raw[18:20] = 0.0 + dets, lit = self.observe(tools) + tp = t - self.t_phase + down = {s: to_side(Q_DOWN, s) for s in SIDES} + + if self.phase == 'down': + for s in SIDES: + self.q_cmd[s] = self.q_cmd[s] + np.clip(down[s] - self.q_cmd[s], -0.05, 0.05) + if t >= T_DOWN: + raw[2] = HIGH + if T_MEAS0 <= t < T_MEAS1: + self.collect(dets, o) + if t >= T_MEAS1: + self.estimate() + self.set_phase('walk' if len(self.sph) == 2 else 'search') + elif self.phase == 'search': + # a sphere was not in view: turn towards its side until it is seen + missing = [s for s in SIDES if s not in self.sph] + if not missing: + self.set_phase('walk') + else: + s = missing[0] + raw[3] = 0.4 if s == 'L' else -0.4 + if tp > 10: + self.collect(dets, o) + self.meas = {k: (v if k == s else []) for k, v in self.meas.items()} + if len(self.meas[s]) >= 6 or tp > 120: + self.estimate() + self.set_phase('walk') + elif self.phase == 'walk': + if not hasattr(self, 'goal'): + self.goal = self.walk_goal(o) + self.log.append(('goal', self.t, self.goal.round(3).tolist())) + goal = self.goal + pos, yaw = pelvis(o) + err_b = _rz(-yaw)[:2, :2] @ (goal - pos[:2]) + dist = np.linalg.norm(err_b) + if dist < 0.02 or tp > 200: + self.set_phase('settle') + else: + v = err_b * 1.5 + v = v / np.linalg.norm(v) * np.clip(np.linalg.norm(v), 0.08, 0.3) + raw[0], raw[1] = v + raw[3] = np.clip(-yaw * 1.0, -0.3, 0.3) + elif self.phase == 'settle': + raw[2] = self.reach_h + settle = 25 if self.reach_h > WALK_HEIGHT - 0.02 else 40 + if tp >= settle - 10: + self.collect(dets, o) + if tp >= settle: + self.estimate() + self.start_tracking(o) + self.set_phase('reach') + elif self.phase == 'reach': + raw[2] = self.reach_h + for s in SIDES: + self.reach_step(s, lit[COLOR_OF[s]], o) + self.track(self.head) + self.hist.append({s: self.q_cmd[s].copy() for s in SIDES}) + # integral action on the shoulder and elbow joints against gravity sag + for s in SIDES: + if self.phase == 'reach' and self.arm[s]['state'] == 'sweep': + qa = o[0:7] if s == 'L' else o[9:16] + for j in (0, 3): # shoulder pitch and elbow carry the arm's weight + self.integ[s][j] = np.clip(self.integ[s][j] + KI * (self.q_cmd[s][j] - qa[j]), -I_MAX, I_MAX) + raw[4:11] = self.q_cmd['L'] + self.integ['L'] + raw[11:18] = self.q_cmd['R'] + self.integ['R'] + return raw diff --git a/policies/reach_target_multi_modal/astra-s1/episodes.csv b/policies/reach_target_multi_modal/astra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..0ca15a678b45c2fc0ed210a75efaf4861ef40156 --- /dev/null +++ b/policies/reach_target_multi_modal/astra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,700,timeout,0 +620001,1,265,success,0 +620002,1,127,success,0 +620003,1,134,success,0 +620004,1,295,success,0 +620005,1,229,success,0 +620006,0,700,timeout,0 +620007,0,700,timeout,0 +620008,0,700,timeout,0 +620009,1,217,success,0 +620010,0,700,timeout,0 +620011,0,700,timeout,0 +620012,1,312,success,0 +620013,0,700,timeout,0 +620014,0,700,timeout,0 +620015,1,283,success,0 +620016,0,700,timeout,0 +620017,1,258,success,0 +620018,1,687,success,0 +620019,0,700,timeout,0 +620020,1,259,success,0 +620021,1,283,success,0 +620022,1,368,success,0 +620023,1,260,success,0 +620024,1,265,success,0 +620025,0,700,timeout,0 +620026,1,197,success,0 +620027,1,141,success,0 +620028,1,338,success,0 +620029,1,262,success,0 +620030,1,449,success,0 +620031,1,244,success,0 +620032,1,227,success,0 +620033,0,700,timeout,0 +620034,1,265,success,0 +620035,0,700,timeout,0 +620036,0,700,timeout,0 +620037,1,252,success,0 +620038,0,700,timeout,0 +620039,1,318,success,0 +620040,1,280,success,0 +620041,1,241,success,0 +620042,1,349,success,0 +620043,1,197,success,0 +620044,0,700,timeout,0 +620045,1,302,success,0 +620046,1,269,success,0 +620047,1,301,success,0 +620048,1,172,success,0 +620049,0,700,timeout,0 +620050,0,700,timeout,0 +620051,1,199,success,0 +620052,1,191,success,0 +620053,0,700,timeout,0 +620054,1,209,success,0 +620055,1,308,success,0 +620056,1,305,success,0 +620057,0,700,timeout,0 +620058,0,700,timeout,0 +620059,1,316,success,0 +620060,1,339,success,0 +620061,1,329,success,0 +620062,1,383,success,0 +620063,1,198,success,0 +620064,1,267,success,0 +620065,0,700,timeout,0 +620066,1,195,success,0 +620067,1,237,success,0 +620068,1,382,success,0 +620069,1,245,success,0 +620070,1,570,success,0 +620071,1,139,success,0 +620072,1,253,success,0 +620073,1,237,success,0 +620074,0,700,timeout,0 +620075,1,247,success,0 +620076,1,235,success,0 +620077,1,208,success,0 +620078,1,192,success,0 +620079,1,355,success,0 +620080,1,288,success,0 +620081,1,227,success,0 +620082,1,385,success,0 +620083,1,239,success,0 +620084,0,700,timeout,0 +620085,1,149,success,0 +620086,1,240,success,0 +620087,1,236,success,0 +620088,1,229,success,0 +620089,1,201,success,0 +620090,1,240,success,0 +620091,1,265,success,0 +620092,1,398,success,0 +620093,1,295,success,0 +620094,1,380,success,0 +620095,1,316,success,0 +620096,0,700,timeout,0 +620097,1,340,success,0 +620098,1,229,success,0 +620099,1,251,success,0 diff --git a/policies/reach_target_multi_modal/astra-s1/policy.py b/policies/reach_target_multi_modal/astra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..af248cf264d5d6991c140741c493bba615727ea0 --- /dev/null +++ b/policies/reach_target_multi_modal/astra-s1/policy.py @@ -0,0 +1,86 @@ +"""Deterministic visual feedback controller for touching the red sphere.""" +import cv2 +import numpy as np + + +def sphere(im): + a=im.astype(float) + m=((a[:,:,0]>25)&(a[:,:,0]>1.65*a[:,:,1])&(a[:,:,0]>1.65*a[:,:,2])).astype(np.uint8) + contours,_=cv2.findContours(m,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE) + if not contours:return None + c=max(contours,key=cv2.contourArea) + if len(c)<5:return None + (x,y),r=cv2.minEnclosingCircle(c) + return np.array([x,y,r]) + + +class Policy: + def reset(self,obs,tools): + self.a=np.array(tools.hold_action(),float) + s=sphere(tools.image('head')) + self.right=s is None or s[0]>41.5 + k=11 if self.right else 4 + self.a[k]=-.2 + self.a[k+2]=.2 if self.right else -.2 + self.h=.74 + self.acquired=s is not None and s[1]>s[2]+2 + self.v=np.zeros(2) + self.xygoal=None + self.lower=False + self.lower_t=0 + + def act(self,obs,tools): + t=obs['t']; p=obs['low_dim_obs'][18:22] + if t%5==0: + s=sphere(tools.image('head')) + if not self.acquired: + if s is not None and s[1]>s[2]+2: + self.acquired=True + self.right=s[0]>41.5 + self.a[4:18]=0 + k=11 if self.right else 4 + self.a[k]=-.2 + self.a[k+2]=.2 if self.right else -.2 + else: + self.v=np.array([.18,0.]) + self.h=.74 + if self.acquired and s is not None and s[2]>2: + x,y,r=s + k=11 if self.right else 4 + nominal_yaw=.2 if self.right else -.2 + dp=self.a[k]+.2 + dyaw=self.a[k+2]-nominal_yaw + goalx=(57 if self.right else 32)-70*dyaw + goaly=21+110*dp+(15 if self.right else -15)*dyaw + goalr=11.5-12*dp + if t>180 and 980 and np.linalg.norm(err)<.035: + self.lower=True + self.lower_t=t + if self.lower and t-self.lower_t>130 and p[2]<.63 and np.linalg.norm(err)>.05: + self.lower=False + self.v=np.clip(err*1.7,-.22,.22) + speed=np.linalg.norm(self.v) + if np.linalg.norm(err)<(.045 if t>180 else .022):self.v[:]=0 + elif speed<.065:self.v*=.065/speed + if self.lower: + self.h=float(np.clip(self.h+np.clip(dz*.25,-.008,.008),.53,.79)) + else:self.h=min(.74,self.h+.008) + self.a[:2]=self.v if t>30 else 0 + self.a[2]=self.h if t>30 else .74 + self.a[3]=np.clip(-p[3]*2,-.4,.4) + return self.a.copy() diff --git a/policies/reach_target_multi_modal/astra-s2/episodes.csv b/policies/reach_target_multi_modal/astra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..c09707525c799aec067affeca9244a0f5a8a6c88 --- /dev/null +++ b/policies/reach_target_multi_modal/astra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,362,success,0 +620001,1,428,success,0 +620002,1,278,success,0 +620003,1,222,success,0 +620004,1,282,success,0 +620005,1,191,success,0 +620006,1,609,success,0 +620007,1,358,success,0 +620008,1,218,success,0 +620009,1,322,success,0 +620010,1,336,success,0 +620011,1,355,success,0 +620012,1,384,success,0 +620013,1,166,success,0 +620014,1,361,success,0 +620015,1,158,success,0 +620016,1,258,success,0 +620017,0,700,timeout,0 +620018,1,355,success,0 +620019,0,700,timeout,0 +620020,1,349,success,0 +620021,1,182,success,0 +620022,1,218,success,0 +620023,1,170,success,0 +620024,1,376,success,0 +620025,1,199,success,0 +620026,1,222,success,0 +620027,1,376,success,0 +620028,1,341,success,0 +620029,1,341,success,0 +620030,1,525,success,0 +620031,1,150,success,0 +620032,1,380,success,0 +620033,1,389,success,0 +620034,1,266,success,0 +620035,1,362,success,0 +620036,1,368,success,0 +620037,1,319,success,0 +620038,1,518,success,0 +620039,1,352,success,0 +620040,1,352,success,0 +620041,1,493,success,0 +620042,1,347,success,0 +620043,1,329,success,0 +620044,1,348,success,0 +620045,1,174,success,0 +620046,1,170,success,0 +620047,1,337,success,0 +620048,1,194,success,0 +620049,1,337,success,0 +620050,1,331,success,0 +620051,1,194,success,0 +620052,1,320,success,0 +620053,1,353,success,0 +620054,1,198,success,0 +620055,1,526,success,0 +620056,1,262,success,0 +620057,1,344,success,0 +620058,1,361,success,0 +620059,1,557,success,0 +620060,1,210,success,0 +620061,1,447,success,0 +620062,1,351,success,0 +620063,1,360,success,0 +620064,1,369,success,0 +620065,0,700,timeout,0 +620066,1,246,success,0 +620067,1,549,success,0 +620068,1,238,success,0 +620069,1,349,success,0 +620070,1,381,success,0 +620071,1,377,success,0 +620072,1,345,success,0 +620073,1,352,success,0 +620074,1,397,success,0 +620075,1,258,success,0 +620076,1,363,success,0 +620077,1,378,success,0 +620078,1,376,success,0 +620079,1,190,success,0 +620080,1,388,success,0 +620081,1,262,success,0 +620082,1,343,success,0 +620083,1,336,success,0 +620084,1,181,success,0 +620085,1,262,success,0 +620086,1,198,success,0 +620087,1,320,success,0 +620088,1,249,success,0 +620089,1,182,success,0 +620090,1,249,success,0 +620091,1,234,success,0 +620092,1,344,success,0 +620093,1,585,success,0 +620094,1,342,success,0 +620095,1,345,success,0 +620096,1,226,success,0 +620097,1,537,success,0 +620098,1,278,success,0 +620099,1,358,success,0 diff --git a/policies/reach_target_multi_modal/astra-s2/policy.py b/policies/reach_target_multi_modal/astra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..cbb1808bc0cfc0bbc8f2207254fea5820f71a06c --- /dev/null +++ b/policies/reach_target_multi_modal/astra-s2/policy.py @@ -0,0 +1,71 @@ +"""Deterministic color-based visual servo for reaching the red sphere. + +The head camera selects an arm. The wrist camera closes the reaching loop; +small base corrections extend the workspace when the arm reaches its limit. +All gains and thresholds below are fixed hand-tuned control constants. +""" +import numpy as np + + +def red(im): + """Return red-pixel centroid, area, and contact-highlight pixel count.""" + z=im.astype(np.int16) + m=(z[:,:,0]>65)&(z[:,:,0]>z[:,:,1]*1.8)&(z[:,:,0]>z[:,:,2]*1.8) + y,x=np.where(m) + if len(x)<3:return None + return float(x.mean()),float(y.mean()),len(x),int(np.sum(m&(z[:,:,0]>240))) + +class Policy: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action()).copy() + # The image horizontal coordinate selects the nearer hand. + f=red(tools.image('head')) + x,y=(f[:2] if f else (42,10)) + self.right=x>=42 + self.i=11 if self.right else 4 + self.cam='right_wrist' if self.right else 'left_wrist' + self.a[self.i:self.i+7]=[np.clip(y*.015-.395,-.5,-.05),0,((63 if self.right else 21)-x)*.012,0,0,0,0] + self.a[18:20]=0 + self.yaw0=float(obs['low_dim_obs'][21]) + def act(self,obs,tools): + t=obs['t'];i=self.i + if t%4==0: + h=red(tools.image('head')) + touch=h and h[3]>=5 + f=red(tools.image(self.cam)) + touch=touch or (f and f[3]>100) + self.a[0:2]=0 + self.a[3]=np.clip((self.yaw0-obs["low_dim_obs"][21])*2,-.3,.3) + # Stop stepping at contact; gently center the sphere while holding. + if touch: + self.a[3]=0 + if f: + self.a[i]+=np.clip((f[1]-42)*.0004,-.01,.01) + self.a[i+1]-=np.clip((f[0]-42)*.0003,-.01,.01) + if t>36 and not touch: + if f: + x,y,n,_=f + if self.a[i+3]>=1.10 and n<6100 and abs(x-42)<22 and abs(y-42)<22: + self.a[0]=.07 + if self.a[i+3]>.6 and abs(x-42)>8: + if (self.right and self.a[i+1]>=.049 and x<42) or (not self.right and self.a[i+1]<=-.049 and x>42): + self.a[1]=np.clip(-(x-42)*.005,-.09,.09) + if abs(self.a[1])<.06:self.a[1]=np.sign(self.a[1])*.06 + self.a[i]+=np.clip((y-42)*.0012,-.03,.03) + + # Shoulder yaw is useful early; roll remains effective + # once the elbow bends and the forearm changes orientation. + if self.a[i+3]<.5: + self.a[i+2]-=np.clip((x-42)*.0008,-.025,.025) + else: + self.a[i+1]-=np.clip((x-42)*.0008,-.025,.025) + if abs(x-42)<15 and abs(y-42)<15 and n<6400 and self.a[i+3]<1.10: + self.a[i+3]+=.023 + self.a[i]-=.023 + else: + if h: + self.a[i]+=.003*np.clip(h[1]-18,-5,5) + self.a[i]=np.clip(self.a[i],-2.2,.3) + self.a[i+1]=np.clip(self.a[i+1],-.7 if self.right else -.05,.05 if self.right else .7) + self.a[i+2]=np.clip(self.a[i+2],-.8,.8) + return self.a.copy() diff --git a/policies/reach_target_multi_modal/astra-s3/episodes.csv b/policies/reach_target_multi_modal/astra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..a97a37e20fa3edfa4c817b0111ed31e7380c5431 --- /dev/null +++ b/policies/reach_target_multi_modal/astra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,119,success,0 +620001,1,443,success,0 +620002,1,287,success,0 +620003,1,534,success,0 +620004,1,138,success,0 +620005,1,475,success,0 +620006,1,245,success,0 +620007,1,102,success,0 +620008,1,95,success,0 +620009,1,150,success,0 +620010,1,98,success,0 +620011,1,169,success,0 +620012,1,149,success,0 +620013,1,522,success,0 +620014,1,249,success,0 +620015,1,455,success,0 +620016,1,96,success,0 +620017,1,139,success,0 +620018,1,366,success,0 +620019,1,140,success,0 +620020,1,123,success,0 +620021,1,159,success,0 +620022,1,126,success,0 +620023,1,357,success,0 +620024,1,108,success,0 +620025,1,454,success,0 +620026,1,586,success,0 +620027,1,229,success,0 +620028,1,151,success,0 +620029,1,150,success,0 +620030,1,246,success,0 +620031,0,700,timeout,0 +620032,1,284,success,0 +620033,1,452,success,0 +620034,1,525,success,0 +620035,1,105,success,0 +620036,0,700,timeout,0 +620037,1,426,success,0 +620038,1,238,success,0 +620039,1,664,success,0 +620040,1,172,success,0 +620041,1,124,success,0 +620042,1,136,success,0 +620043,1,171,success,0 +620044,1,104,success,0 +620045,1,167,success,0 +620046,1,159,success,0 +620047,1,248,success,0 +620048,1,275,success,0 +620049,1,100,success,0 +620050,1,104,success,0 +620051,1,236,success,0 +620052,1,413,success,0 +620053,1,144,success,0 +620054,1,155,success,0 +620055,1,153,success,0 +620056,1,367,success,0 +620057,1,103,success,0 +620058,1,123,success,0 +620059,1,174,success,0 +620060,1,96,success,0 +620061,1,296,success,0 +620062,1,127,success,0 +620063,0,700,timeout,0 +620064,1,387,success,0 +620065,1,256,success,0 +620066,1,359,success,0 +620067,1,186,success,0 +620068,1,96,success,0 +620069,1,427,success,0 +620070,1,437,success,0 +620071,1,427,success,0 +620072,1,124,success,0 +620073,1,105,success,0 +620074,1,122,success,0 +620075,1,440,success,0 +620076,1,160,success,0 +620077,1,367,success,0 +620078,1,241,success,0 +620079,1,95,success,0 +620080,1,123,success,0 +620081,0,700,timeout,0 +620082,1,122,success,0 +620083,1,100,success,0 +620084,1,157,success,0 +620085,1,356,success,0 +620086,1,153,success,0 +620087,1,609,success,0 +620088,0,700,timeout,0 +620089,1,231,success,0 +620090,1,185,success,0 +620091,1,455,success,0 +620092,1,120,success,0 +620093,1,189,success,0 +620094,1,136,success,0 +620095,1,150,success,0 +620096,1,96,success,0 +620097,1,124,success,0 +620098,1,440,success,0 +620099,1,426,success,0 diff --git a/policies/reach_target_multi_modal/astra-s3/policy.py b/policies/reach_target_multi_modal/astra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..0ff2933bd8dbdeb2d533b389b7853285ba19602f --- /dev/null +++ b/policies/reach_target_multi_modal/astra-s3/policy.py @@ -0,0 +1,120 @@ +"""Deterministic visual reaching controller for the G1. + +Color segmentation supplies the sphere center, angular size, and visible +contact feedback. A coarse pinhole model guides the approach, followed by +height adjustment. High targets use a raised arm and image-based base servo. +All control constants are hand tuned; there are no learned components. +""" + +import numpy as np +import cv2 + +# Perception uses only the on-robot RGB image. +def detect(im): + r, g, b = im.astype(float).transpose(2, 0, 1) + mask = ((r > 25) & (r > 1.6 * g) & (r > 1.6 * b)).astype('uint8') + n, lab, stats, cent = cv2.connectedComponentsWithStats(mask) + if n < 2: + return None + i = 1 + np.argmax(stats[1:, 4]) + ys, xs = np.where(lab == i) + (x, y), rad = cv2.minEnclosingCircle(np.array([xs, ys]).T.astype('float32')) + bright = np.sum(r[lab == i] > 230) + return np.array([x, y, rad, bright], float) + +def red(im): + return detect(im) + +class Policy: + + def reset(self, obs, tools): + self.a = np.array(tools.hold_action()) + self.yaw = obs['low_dim_obs'][21] + self.side = 1 + self.phase = 0 + self.start = 0 + self.height = 0.74 + self.contact = 0 + self.arm = np.zeros(7) + self.seen = False + self.highmode = False + z = detect(tools.image('head')) + if z is not None: + self.side = 1 if z[0] > 42 else -1 + self.seen = True + + def act(self, obs, tools): + a = self.a.copy() + t = obs['t'] + q = obs['low_dim_obs'] + a[:4] = [0, 0, self.height, np.clip(2 * (self.yaw - q[21]), -0.4, 0.4)] + idx = 11 if self.side == 1 else 4 + a[idx:idx + 7] = self.arm + z = detect(tools.image('head')) + if z is None: + if self.phase == 0: + a[0] = 0.12 + return a + if not self.seen: + self.side = 1 if z[0] > 42 else -1 + self.seen = True + if z[1] < 5 and self.phase == 0: + a[0] = 0.16 + return a + # Hold long enough for sustained contact despite short occlusions. + if z[3] > 8: + self.contact = t + if self.contact and t - self.contact < 65: + return a + if t > 250 and self.height > 0.84: + self.highmode = True + # Walk at normal pelvis height when using the raised-arm reach. + if self.highmode: + self.arm += np.clip(np.array([-1.2, 0, 0, 1.2, 0, 0, 0]) - self.arm, -0.015, 0.015) + a[idx:idx + 7] = self.arm + self.height = 0.74 + a[2] = 0.74 + ex = z[0] - (53 if self.side == 1 else 30) + ey = 6 - z[1] + if abs(ex) > 2: + a[1] = -np.sign(ex) * np.clip(abs(ex) * 0.012, 0.06, 0.15) + if abs(ey) > 2: + a[0] = np.sign(ey) * np.clip(abs(ey) * 0.01, 0.06, 0.15) + return a + u = 67 if self.side == 1 else 16 + v = 43 + radius = 8.0 + # Approximate camera geometry is used as a feedback scale. + dep = 55 * 0.04 / z[2] + dep0 = 55 * 0.04 / radius + vv = (z[1] - 41.5) * dep / 55 + vv0 = (v - 41.5) * dep0 / 55 + dx = 0.5 * (dep - dep0) - 0.866 * (vv - vv0) + dz = -0.866 * (dep - dep0) - 0.5 * (vv - vv0) + dy = -((z[0] - 41.5) * dep - (u - 41.5) * dep0) / 55 + if self.phase == 0: + if abs(dx) > 0.012: + a[0] = np.sign(dx) * np.clip(abs(dx) * 2, 0.06, 0.22) + if abs(dy) > 0.012: + a[1] = np.sign(dy) * np.clip(abs(dy) * 2, 0.06, 0.18) + if abs(dx) < 0.018 and abs(dy) < 0.018 and (t > 70) or t > 300: + self.phase = 1 + self.start = t + else: + if t % 10 == 0: + self.height = np.clip(self.height + 0.4 * dz, 0.45, 0.87) + a[2] = self.height + if t > 230 and self.height > 0.84 or t > 460: + l1 = 0.185 + l2 = 0.24 + zz = -(l1 + l2) + dz + yy = dy + roll = np.clip(np.arctan2(yy, -zz), -0.45, 0.45) + zz = -np.hypot(zz, yy) + cc = np.clip((dx * dx + zz * zz - l1 * l1 - l2 * l2) / (2 * l1 * l2), -0.95, 1) + el = np.arccos(cc) + pitch = np.arctan2(-dx, -zz) - np.arctan2(l2 * np.sin(el), l1 + l2 * np.cos(el)) + goal = np.array([pitch, roll, 0, el, 0, 0, 0]) + self.arm += np.clip(goal - self.arm, -0.015, 0.015) + a[idx:idx + 7] = self.arm + return a diff --git a/policies/reach_target_multi_modal/deepseek1017-s1/episodes.csv b/policies/reach_target_multi_modal/deepseek1017-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..d4259e14792ad4d9aececc823bab7ba61bf11e96 --- /dev/null +++ b/policies/reach_target_multi_modal/deepseek1017-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,700,timeout,0 +620001,0,700,timeout,0 +620002,0,700,timeout,0 +620003,0,700,timeout,0 +620004,0,700,timeout,0 +620005,0,700,timeout,0 +620006,0,700,timeout,0 +620007,0,700,timeout,0 +620008,0,700,timeout,0 +620009,0,700,timeout,0 +620010,0,700,timeout,0 +620011,0,700,timeout,0 +620012,0,700,timeout,0 +620013,0,700,timeout,0 +620014,0,700,timeout,0 +620015,0,700,timeout,0 +620016,0,700,timeout,0 +620017,0,700,timeout,0 +620018,0,700,timeout,0 +620019,0,700,timeout,0 +620020,0,700,timeout,0 +620021,0,700,timeout,0 +620022,0,700,timeout,0 +620023,0,700,timeout,0 +620024,0,700,timeout,0 +620025,0,700,timeout,0 +620026,0,700,timeout,0 +620027,0,700,timeout,0 +620028,0,700,timeout,0 +620029,0,700,timeout,0 +620030,0,700,timeout,0 +620031,0,700,timeout,0 +620032,0,700,timeout,0 +620033,0,700,timeout,0 +620034,0,700,timeout,0 +620035,0,700,timeout,0 +620036,0,700,timeout,0 +620037,0,700,timeout,0 +620038,0,700,timeout,0 +620039,0,700,timeout,0 +620040,0,700,timeout,0 +620041,0,700,timeout,0 +620042,0,700,timeout,0 +620043,0,700,timeout,0 +620044,0,700,timeout,0 +620045,0,700,timeout,0 +620046,0,700,timeout,0 +620047,0,700,timeout,0 +620048,0,700,timeout,0 +620049,0,700,timeout,0 +620050,0,700,timeout,0 +620051,0,700,timeout,0 +620052,0,700,timeout,0 +620053,0,700,timeout,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,0,700,timeout,0 +620058,0,700,timeout,0 +620059,0,700,timeout,0 +620060,0,700,timeout,0 +620061,0,700,timeout,0 +620062,0,700,timeout,0 +620063,0,700,timeout,0 +620064,0,700,timeout,0 +620065,0,700,timeout,0 +620066,0,700,timeout,0 +620067,0,700,timeout,0 +620068,0,700,timeout,0 +620069,0,700,timeout,0 +620070,0,700,timeout,0 +620071,0,700,timeout,0 +620072,0,700,timeout,0 +620073,0,700,timeout,0 +620074,0,700,timeout,0 +620075,0,700,timeout,0 +620076,0,700,timeout,0 +620077,0,700,timeout,0 +620078,0,700,timeout,0 +620079,0,700,timeout,0 +620080,0,700,timeout,0 +620081,0,700,timeout,0 +620082,0,700,timeout,0 +620083,0,700,timeout,0 +620084,0,700,timeout,0 +620085,0,700,timeout,0 +620086,0,700,timeout,0 +620087,0,700,timeout,0 +620088,0,700,timeout,0 +620089,0,700,timeout,0 +620090,0,700,timeout,0 +620091,0,700,timeout,0 +620092,0,700,timeout,0 +620093,0,700,timeout,0 +620094,0,700,timeout,0 +620095,0,700,timeout,0 +620096,0,700,timeout,0 +620097,0,700,timeout,0 +620098,0,700,timeout,0 +620099,0,700,timeout,0 diff --git a/policies/reach_target_multi_modal/deepseek1017-s1/policy.py b/policies/reach_target_multi_modal/deepseek1017-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..73ab7841bce0eff7021d3b602367331781a399a9 --- /dev/null +++ b/policies/reach_target_multi_modal/deepseek1017-s1/policy.py @@ -0,0 +1,721 @@ +"""Hand-written visual servoing policy: touch the red sphere with either hand. + +The policy is a deterministic state machine using only the robot's own cameras +and proprioception: + + 1. settle, then find the red sphere (head camera; fall back to the wrist + cameras and then to a slow in-place yaw scan); + 2. choose the hand on the side the sphere appears on; + 3. get the sphere into that hand's wrist camera by sweeping the tilt/pan + joints of the arm (the wrist camera looks roughly along the hand, so it + is the natural approach sensor); + 4. learn, with a few small joint probes, how the pan/tilt joints move the + sphere in that image, and centre it; + 5. learn the radial gradient of the apparent sphere radius with respect to + the arm joints and push the hand towards the sphere until the sphere is + large in the image (i.e. the hand is at it), re-centring as needed; + 6. if the wrist camera cannot acquire the sphere, aim the hand at the + sphere's head-camera bearing first (a small image Jacobian is identified + by probing), then repeat 3-5; + 7. hold the final pose for the second of continuous contact the task needs. + +The probing is online system identification of the current robot, not a +learned model, and everything is closed loop on the images: no camera +calibration, sphere size or exact link lengths are assumed. The base is never +commanded to move (only a slow yaw scan if the sphere is nowhere in view), so +the robot stays on its feet. +""" + +import os + +import cv2 +import numpy as np + +IMG = 84 +CX = (IMG - 1) * 0.5 +CY = (IMG - 1) * 0.5 + +# ---------------------------------------------------------------------------- +# perception +# ---------------------------------------------------------------------------- + + +def _chan(im): + a = im.astype(np.int16) + return a[..., 0], a[..., 1], a[..., 2] + + +def red_mask(im): + """Red target mask; also catches the dark shadowed side of the sphere.""" + r, g, b = _chan(im) + return ((r > 25) & (r > g + 18) & (r > b + 18)).astype(np.uint8) + + +def white_mask(im): + """White robot mask (the room behind the robot is blue).""" + r, g, b = _chan(im) + return ((r > 115) & (g > 115) & (b > 105) & (np.abs(r - b) < 45)).astype(np.uint8) + + +def find_sphere(im, min_area=15): + """Largest red blob in an image -> dict(u, v, area, r) or None.""" + m = red_mask(im) + if int(m.sum()) < min_area: + return None + n, lab, st, ce = cv2.connectedComponentsWithStats(m, 8) + if n <= 1: + return None + i = 1 + int(np.argmax(st[1:, cv2.CC_STAT_AREA])) + area = float(st[i, cv2.CC_STAT_AREA]) + if area < min_area: + return None + return {"u": float(ce[i][0]), "v": float(ce[i][1]), "area": area, + "r": float(np.sqrt(area / np.pi))} + + +def find_red_all(im, min_area=8): + """All red pixels (robust when the sphere is clipped by the frame edge).""" + m = red_mask(im) + area = int(m.sum()) + if area < min_area: + return None + ys, xs = np.nonzero(m) + return {"u": float(xs.mean()), "v": float(ys.mean()), "area": float(area), + "r": float(np.sqrt(area / np.pi))} + + +def arm_blob(im, side): + """White arm blob in the head image. + + The arm is the big white component that reaches into the lower part of the + frame on the requested side of the image. ``tip`` is the point furthest + from the lowest (body) end of that component - i.e. the hand end. + """ + m = white_mask(im) + if int(m.sum()) < 20: + return None + n, lab, st, ce = cv2.connectedComponentsWithStats(m, 8) + best, best_score = -1, -1.0 + for i in range(1, n): + area = float(st[i, cv2.CC_STAT_AREA]) + if area < 25: + continue + x, y, w, h = st[i, :4] + if y + h < 45: + continue + cx = float(ce[i][0]) + if side < 0 and cx > 60: + continue + if side > 0 and cx < 24: + continue + score = area + (500.0 if y + h >= IMG - 2 else 0.0) + if score > best_score: + best, best_score = i, score + if best < 0: + return None + ys, xs = np.nonzero(lab == best) + j = int(np.argmax(ys)) + root = (float(xs[j]), float(ys[j])) + d2 = (xs - root[0]) ** 2 + (ys - root[1]) ** 2 + k = max(1, min(25, len(d2))) + idx = np.argpartition(d2, len(d2) - k)[-k:] + tip = (float(xs[idx].mean()), float(ys[idx].mean())) + return {"tip": tip, "root": root, "area": float(len(xs))} + + +# generous joint ranges for the 7 arm joints +LIMITS = np.array([[-3.10, 2.70], [-2.00, 2.30], [-2.60, 2.60], + [-2.20, 2.40], [-2.00, 2.00], [-1.70, 1.70], + [-1.70, 1.70]], dtype=np.float64) + +RATE = 0.06 # normal joint target slew per step (rad) +ACQ_RATE = 0.22 # slew while searching for the sphere +HEAD_DELTA = 0.09 # head-camera arm probe amplitude (rad) +HEAD_WAIT = 8 +HEAD_JOINTS = (0, 1, 3) # shoulder pitch, shoulder roll, elbow +ARM_COLS = (0, 1, 2, 3) + +R_GOAL = 32.0 +K_R = 26.0 + + +class Policy: + """One episode of reaching the red sphere.""" + + def __init__(self): + self.gen = None + + # ------------------------------------------------------------------ + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float64).reshape(-1) + ld = np.asarray(obs["low_dim_obs"], dtype=np.float64) + self.q0 = [ld[0:7].copy(), ld[9:16].copy()] + self.hold[4:11] = self.q0[0] + self.hold[11:18] = self.q0[1] + self.cmd = self.hold.copy() + self.tgt = self.hold.copy() + self.height = float(self.hold[2]) + self.time_limit = int(obs.get("time_limit") or 1000) + self.t = 0 + self.arm = 0 + self.sphere = None + self.last_tip = None + self.vx = 0.0 + self.yaw = 0.0 + self._Jc = None + self.PAN, self.TILT = 2, 5 + self.last_best_r = 0.0 + self.debug = bool(os.environ.get("POLICY_DEBUG")) + self.trace = [] + self.gen = None + self.done = False + + # ------------------------------------------------------------------ + def _log(self, msg): + if self.debug: + self.trace.append((self.t, str(msg))) + + def raw(self, rate=RATE): + for base in (4, 11): + for i in range(7): + d = self.tgt[base + i] - self.cmd[base + i] + self.cmd[base + i] += float(np.clip(d, -rate, rate)) + self.cmd[0] = self.vx + self.cmd[1] = 0.0 + self.cmd[2] = self.height + self.cmd[3] = self.yaw + return self.cmd.astype(np.float32) + + def base(self): + return 4 if self.arm == 0 else 11 + + def tgt_j(self, j): + return float(self.tgt[self.base() + j]) + + def set_j(self, j, v): + self.tgt[self.base() + j] = float(np.clip(v, LIMITS[j, 0], LIMITS[j, 1])) + + def cam(self): + return "left_wrist" if self.arm == 0 else "right_wrist" + + def qa(self, obs, j): + ld = np.asarray(obs["low_dim_obs"], dtype=np.float64) + return float(ld[(0 if self.arm == 0 else 9) + j]) + + def wrist_red(self, tools): + return find_red_all(tools.image(self.cam())) + + # ------------------------------------------------------------------ + def act(self, obs, tools): + try: + if self.gen is None: + self.gen = self.control_loop() + next(self.gen) + self.t += 1 + return self.gen.send((obs, tools)) + except StopIteration: + self.done = True + return self.raw() + except Exception as exc: # never let a policy bug kill the episode + import traceback + self._log(f"EXC {exc!r}\n{traceback.format_exc()}") + self.done = True + return self.raw() + + def step(self, rate=RATE): + obs, tools = yield self.raw(rate) + return obs, tools + + def wait(self, n): + obs = tools = None + for _ in range(n): + obs, tools = yield from self.step() + return obs, tools + + # ------------------------------------------------------------------ + def measure_head(self, tools, n=1): + us, vs, ar, tips = [], [], [], [] + for _ in range(max(1, n)): + im = tools.image("head") + sp = find_sphere(im) + if sp is not None: + us.append(sp["u"]); vs.append(sp["v"]); ar.append(sp["area"]) + ab = arm_blob(im, -1 if self.arm == 0 else 1) + if ab is not None: + tips.append(ab["tip"]) + sp = None + if us: + area = float(np.mean(ar)) + sp = {"u": float(np.mean(us)), "v": float(np.mean(vs)), + "area": area, "r": float(np.sqrt(area / np.pi))} + tip = None + if tips: + tip = (float(np.mean([t[0] for t in tips])), + float(np.mean([t[1] for t in tips]))) + return sp, tip + + # ------------------------------------------------------------------ + def control_loop(self): + obs, tools = yield self.raw() + obs, tools = yield from self.wait(3) + head = find_sphere(tools.image("head")) + left = find_red_all(tools.image("left_wrist")) + right = find_red_all(tools.image("right_wrist")) + self._log(f"head={head} left={left} right={right}") + if head is not None: + self.arm = 0 if head["u"] <= CX + 5.0 else 1 + elif left is not None or right is not None: + self.arm = 0 if (left or {}).get("area", 0) >= (right or {}).get("area", 0) else 1 + self.sphere = head + if left is not None and right is None: + self.arm = 0 + elif right is not None and left is None: + self.arm = 1 + self._log(f"arm={self.arm}") + + # 1) the wrist camera can see the sphere: approach with it + if (yield from self.acquire(tools)): + yield from self.wrist_servo(tools) + if self.last_best_r > R_GOAL * 0.55: + yield from self.press_hold() + return + self._log(f"servo weak ({self.last_best_r:.1f}), retrying") + + + # 2) aim the hand with the head camera, then use the wrist camera again + if head is not None and self.t < self.time_limit - 150: + J = yield from self.probe_head(tools) + if J is not None: + yield from self.head_reach(tools, J) + if (yield from self.acquire(tools)): + yield from self.wrist_servo(tools) + yield from self.press_hold() + return + elif head is None: + obs, tools = yield from self.search() + head = find_sphere(tools.image("head")) + if head is not None: + self.arm = 0 if head["u"] <= CX + 5.0 else 1 + J = yield from self.probe_head(tools) + if J is not None: + yield from self.head_reach(tools, J) + if (yield from self.acquire(tools)): + yield from self.wrist_servo(tools) + yield from self.press_hold() + return + + # 3) if the other wrist camera sees the sphere, use that hand + other = 1 - self.arm + cam = "right_wrist" if other == 1 else "left_wrist" + if find_red_all(tools.image(cam)) is not None and self.t < self.time_limit - 120: + self._log(f"switch to other hand {other}") + self.arm = other + if (yield from self.acquire(tools)): + yield from self.wrist_servo(tools) + yield from self.press_hold() + return + self.arm = 1 - other + + # 4) last resort: sweep the arms and press + yield from self.blind_reach() + yield from self.press_hold() + + # ------------------------------------------------------------------ + def search(self): + """Slow in-place yaw scan (only when nothing sees the sphere).""" + self._log("search") + obs = tools = None + self.yaw = 0.20 + for _ in range(50): + obs, tools = yield from self.step() + if (find_sphere(tools.image("head")) is not None + or find_red_all(tools.image("left_wrist")) is not None + or find_red_all(tools.image("right_wrist")) is not None): + break + self.yaw = 0.0 + obs, tools = yield from self.wait(1) + return obs, tools + + # ------------------------------------------------------------------ + def probe_head(self, tools): + """d(arm tip - sphere)/dq from the head camera, for [SP, SR, EL].""" + obs = None + for j in range(7): + self.set_j(j, self.q0[self.arm][j]) + obs, tools = yield from self.wait(3) + e0, tip0, sp0 = self.head_err(tools) + if e0 is None: + return None + J = np.zeros((2, 3)) + for col, j in enumerate(HEAD_JOINTS): + q = self.tgt_j(j) + got = None + for sgn in (1.0, -1.0): + self.set_j(j, q + sgn * HEAD_DELTA) + obs, tools = yield from self.wait(HEAD_WAIT) + e1, tip1, sp1 = self.head_err(tools) + if e1 is not None and e0 is not None: + cand = (e1 - e0) / (sgn * HEAD_DELTA) + if float(np.hypot(*cand)) > 2.0: + got = cand + e0 = e1 + break + self.set_j(j, q) + obs, tools = yield from self.wait(HEAD_WAIT) + e0b, _, _ = self.head_err(tools) + if e0b is not None: + e0 = e0b + if got is None: + self._log(f"head probe j{j} failed") + continue + J[:, col] = got + self._log(f"head probe j{j} {np.round(got, 1).tolist()}") + for j in range(7): + self.set_j(j, self.q0[self.arm][j]) + obs, tools = yield from self.wait(HEAD_WAIT) + return J + + def head_err(self, tools): + sp, tip = self.measure_head(tools, 1) + if sp is None or tip is None: + return None, None, None + return np.array([tip[0] - sp["u"], tip[1] - sp["v"]]), tip, sp + + def bearing_step(self, J, e, max_img=2.0): + if J is None or not np.all(np.isfinite(J)): + return np.zeros(3) + norms = np.linalg.norm(J, axis=0) + norms = np.where(norms < 1e-6, 1e-6, norms) + Jn = J / norms + try: + dqn = -Jn.T @ np.linalg.solve(Jn @ Jn.T + 0.30 * np.eye(2), e) * 0.6 + except np.linalg.LinAlgError: + return np.zeros(3) + dq = dqn / norms + pred = J @ dq + npred = float(np.linalg.norm(pred)) + if npred > max_img: + dq *= max_img / npred + return np.clip(dq, -0.04, 0.04) + + def out_dir(self, J, sp, tip): + """Joint-space directions that move the hand away from the body.""" + if J is None: + return np.zeros(3) + o = np.array([sp["u"] - CX * 0.7, sp["v"] - IMG * 0.9]) + o = o / (np.hypot(*o) + 1e-6) + return np.array([float(np.sign(J[0, k] * o[0] + J[1, k] * o[1])) + for k in range(3)]) + + def head_reach(self, tools, J): + """Servo the hand onto the sphere's bearing until the wrist sees it.""" + obs = None + prev_tip = None + aligned = 0 + for it in range(24): + sp, tip = self.measure_head(tools, 1) + if prev_tip is not None and tip is not None: + if np.hypot(tip[0] - prev_tip[0], tip[1] - prev_tip[1]) > 26: + tip = None + if sp is None or tip is None: + obs, tools = yield from self.wait(2) + continue + prev_tip = tip + self.sphere = sp + wr = self.wrist_red(tools) + if wr is not None and wr["area"] > 30: + self._log(f"wrist acquired it={it} {wr}") + return + e = np.array([tip[0] - sp["u"], tip[1] - sp["v"]]) + n = float(np.hypot(*e)) + if it % 4 == 0: + self._log(f"head reach it={it} tip={np.round(tip,1).tolist()} " + f"sp={np.round([sp['u'],sp['v']],1).tolist()} n={n:.1f}") + if n < 4.0: + aligned += 1 + else: + aligned = 0 + dq = self.bearing_step(J, e) + for col, j in enumerate(HEAD_JOINTS): + self.set_j(j, self.tgt_j(j) + float(dq[col])) + if aligned >= 2: + od = self.out_dir(J, sp, tip) + for col, j in enumerate(HEAD_JOINTS): + self.set_j(j, self.tgt_j(j) + 0.02 * float(od[col])) + obs, tools = yield from self.wait(5) + self._log("head reach end") + + # ------------------------------------------------------------------ + def sweep_to(self, j, v): + """Move joint j toward v, checking the wrist camera every step.""" + obs = tools = None + self.set_j(j, v) + for _ in range(36): + obs, tools = yield from self.step(ACQ_RATE) + r = self.wrist_red(tools) + if r is not None and r["area"] > 25: + return obs, tools, r + if abs(self.qa(obs, j) - self.tgt_j(j)) < 0.05: + break + return obs, tools, None + + def acquire(self, tools): + """Sweep the wrist joints until the sphere enters the wrist camera.""" + obs = None + r = self.wrist_red(tools) + if r is not None: + self._log(f"wrist already sees {r}") + return True + for j, amp in ((5, 1.15), (2, 0.75)): + q = self.q0[self.arm][j] + for direction in (-1.0, 1.0): + self._log(f"acq sweep j{j} dir={direction}") + self.set_j(j, q) + obs, tools = yield from self.wait(2) + obs, tools, r = yield from self.sweep_to(j, q + direction * amp) + if r is not None: + self.set_j(j, self.qa(obs, j)) + obs, tools = yield from self.wait(2) + yield from self.centre_after_find(j, direction, tools) + return True + self._log("acq failed") + return False + + def centre_after_find(self, j, direction, tools): + """Keep moving the joint in the sweep direction while the sphere centres.""" + obs = None + def dist(r): + return float(np.hypot(r["u"] - CX, r["v"] - CY)) + r = self.wrist_red(tools) + if r is None: + return + best = dist(r) + bestq = self.tgt_j(j) + miss = 0 + for _ in range(16): + self.set_j(j, self.tgt_j(j) + direction * 0.05) + obs, tools = yield from self.wait(3) + r = self.wrist_red(tools) + if r is None: + miss += 1 + if miss >= 2: + break + continue + d = dist(r) + if d < best - 0.5: + best = d + bestq = self.tgt_j(j) + miss = 0 + else: + miss += 1 + if miss >= 2: + break + self.set_j(j, bestq) + obs, tools = yield from self.wait(3) + self._log(f"centred j{j} at {bestq:.2f} dist={best:.1f}") + + # ------------------------------------------------------------------ + def blind_reach(self): + """Last resort when the sphere never appeared in a wrist camera.""" + obs, tools = None, None + for arm in (self.arm, 1 - self.arm): + self.arm = arm + for j, span in ((0, (0.5, 0.25, 0.0, -0.25, -0.5)), + (3, (0.5, 0.25, 0.0, -0.25, -0.5))): + for dv in span: + self.set_j(j, self.q0[arm][j] + dv) + obs, tools = yield from self.wait(8) + r = self.wrist_red(tools) + if r is not None and r["area"] > 25: + yield from self.wrist_servo(tools) + return + yield from self.press_hold() + + # ------------------------------------------------------------------ + def feat(self, tools): + blob = self.wrist_red(tools) + if blob is None: + return None + return np.array([blob["u"], blob["v"], + K_R * np.log(max(blob["r"], 0.6))]) + + PAN, TILT = 2, 5 + + def centre_wrist(self, tools, iters=10, tol=7.0, learn=False, pair=None): + """Centre the sphere with a pan and a tilt joint of the reaching arm.""" + if pair is not None: + self.PAN, self.TILT = pair + obs = None + Jc = getattr(self, "_Jc", None) + if learn or Jc is None: + blob = self.wrist_red(tools) + if blob is None: + return + f0 = np.array([blob["u"], blob["v"]]) + cols = {} + for j in (1, 2, 5): + q = self.tgt_j(j) + got = None + for sgn in (1.0, -1.0): + self.set_j(j, q + sgn * 0.08) + obs, tools = yield from self.wait(4) + b1 = self.wrist_red(tools) + self.set_j(j, q) + obs, tools = yield from self.wait(4) + if b1 is not None: + got = (np.array([b1["u"], b1["v"]]) - f0) / (sgn * 0.08) + break + b0 = self.wrist_red(tools) + if b0 is not None: + f0 = np.array([b0["u"], b0["v"]]) + if got is not None: + cols[j] = got + if len(cols) >= 2: + order = sorted(cols, key=lambda k: -np.linalg.norm(cols[k])) + self.PAN, self.TILT = order[0], order[1] + elif len(cols) == 1: + j = list(cols)[0] + self.PAN, self.TILT = j, (5 if j != 5 else 2) + Jc = np.zeros((2, 2)) + if self.PAN in cols: + Jc[:, 0] = cols[self.PAN] + if self.TILT in cols: + Jc[:, 1] = cols[self.TILT] + self._Jc = Jc + self._log(f"centre pair=({self.PAN},{self.TILT}) J={np.round(Jc,1).tolist()}") + for _ in range(iters): + blob = self.wrist_red(tools) + if blob is None: + return + e = np.array([blob["u"] - CX, blob["v"] - CY]) + if np.hypot(*e) < tol: + return + if np.linalg.norm(Jc[:, 0]) < 8.0 and np.linalg.norm(Jc[:, 1]) < 8.0: + return + try: + dq = -np.linalg.solve(Jc + 0.4 * np.eye(2), e) * 0.6 + except np.linalg.LinAlgError: + return + dq = np.clip(dq, -0.10, 0.10) + for k, j in enumerate((self.PAN, self.TILT)): + self.set_j(j, self.tgt_j(j) + float(dq[k])) + obs, tools = yield from self.wait(3) + + def probe_arm_radial(self, tools): + """Radial derivative of the reaching arm joints in the wrist image.""" + obs = None + grad = {} + f0 = self.feat(tools) + if f0 is None: + return None + for j in (0, 1, 3): + q = self.tgt_j(j) + best = 0.0 + delta = 0.12 + for sgn in (1.0, -1.0): + self.set_j(j, q + sgn * delta) + obs, tools = yield from self.wait(4) + f1 = self.feat(tools) + self.set_j(j, q) + obs, tools = yield from self.wait(4) + if f1 is not None: + best = (f1[2] - f0[2]) / (sgn * delta) + break + f0b = self.feat(tools) + if f0b is not None: + f0 = f0b + if abs(best) > 0.8: + grad[j] = best + self._log(f"radial j{j} {best:.1f}") + if not grad: + return None + return grad + + def wrist_servo(self, tools, quick=False): + """Centre the sphere, then push the hand at it until the sphere is big.""" + obs = None + self._log(f"wrist_servo quick={quick}") + yield from self.centre_wrist(tools, iters=8, learn=True) + best = 0.0 + joint = None + sign = 1.0 + flat = 0 + grad = None + lost = 0 + for it in range(55 if quick else 80): + if self.t >= self.time_limit - 70: + break + blob = self.wrist_red(tools) + if blob is None: + lost += 1 + obs, tools = yield from self.wait(2) + if lost > 10: + self._log("servo lost sphere") + self.last_best_r = best + return + continue + lost = 0 + rad = max(blob["r"], 0.6) + e2 = float(np.hypot(blob["u"] - CX, blob["v"] - CY)) + best = max(best, rad) + self.last_best_r = best + if it % 5 == 0: + self._log(f"wservo it={it} u={blob['u']:.1f} v={blob['v']:.1f} " + f"r={rad:.1f} e2={e2:.1f} j={joint}") + if rad > R_GOAL * 0.92 and e2 < 13.0: + self._log(f"contact r={rad:.1f} it={it}") + # a couple of gentle extra pushes so the fingers really touch + if joint is not None: + for _ in range(3): + q = self.tgt_j(joint) + self.set_j(joint, q + sign * 0.08) + obs, tools = yield from self.wait(4) + yield from self.centre_wrist(tools, iters=2) + return + if e2 > 14.0 or joint is None: + yield from self.centre_wrist(tools, iters=3) + blob = self.wrist_red(tools) + if blob is None: + continue + rad = max(blob["r"], 0.6) + best = max(best, rad) + if joint is None or flat >= 2: + if grad is None or flat >= 3: + grad = yield from self.probe_arm_radial(tools) + flat = 0 + if not grad: + return + joint = max(grad, key=lambda k: abs(grad[k])) + sign = 1.0 if grad[joint] >= 0 else -1.0 + self._log(f"choose joint {joint} sign {sign:.0f} grad={grad}") + q = self.tgt_j(joint) + self.set_j(joint, q + sign * 0.15) + obs, tools = yield from self.wait(6) + b2 = self.wrist_red(tools) + if b2 is None: + self.set_j(joint, q) + obs, tools = yield from self.wait(4) + lost += 1 + if lost > 6: + self.last_best_r = best + return + yield from self.centre_wrist(tools, iters=3, learn=True) + grad = None + joint = None + continue + r2 = max(b2["r"], 0.6) + if r2 > rad + 0.12: + flat = 0 + else: + self.set_j(joint, q) + obs, tools = yield from self.wait(4) + flat += 1 + joint = None + if it % 3 == 2: + yield from self.centre_wrist(tools, iters=2) + self.last_best_r = best + self._log(f"wservo end best_r={best:.1f}") + + def press_hold(self): + """Keep the pose for the 1 s of continuity the task requires.""" + yield from self.wait(75) diff --git a/policies/reach_target_multi_modal/deepseek1017-s2/episodes.csv b/policies/reach_target_multi_modal/deepseek1017-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..1f8876643364de2fc1d8b92be2117da18fda91a9 --- /dev/null +++ b/policies/reach_target_multi_modal/deepseek1017-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,700,timeout,0 +620001,0,700,timeout,0 +620002,0,700,timeout,0 +620003,0,700,timeout,0 +620004,0,700,timeout,0 +620005,0,700,timeout,0 +620006,0,700,timeout,0 +620007,0,700,timeout,0 +620008,0,700,timeout,0 +620009,0,700,timeout,0 +620010,0,700,timeout,0 +620011,0,700,timeout,0 +620012,1,209,success,0 +620013,0,700,timeout,0 +620014,0,700,timeout,0 +620015,0,700,timeout,0 +620016,0,700,timeout,0 +620017,1,141,success,0 +620018,0,700,timeout,0 +620019,1,195,success,0 +620020,0,700,timeout,0 +620021,0,700,timeout,0 +620022,0,700,timeout,0 +620023,0,700,timeout,0 +620024,1,224,success,0 +620025,0,700,timeout,0 +620026,0,700,timeout,0 +620027,0,700,timeout,0 +620028,0,700,timeout,0 +620029,0,700,timeout,0 +620030,0,700,timeout,0 +620031,0,700,timeout,0 +620032,0,700,timeout,0 +620033,0,700,timeout,0 +620034,0,700,timeout,0 +620035,0,700,timeout,0 +620036,0,700,timeout,0 +620037,0,700,timeout,0 +620038,0,700,timeout,0 +620039,0,700,timeout,0 +620040,0,700,timeout,0 +620041,0,700,timeout,0 +620042,0,700,timeout,0 +620043,0,700,timeout,0 +620044,0,700,timeout,0 +620045,0,700,timeout,0 +620046,0,700,timeout,0 +620047,1,145,success,0 +620048,0,700,timeout,0 +620049,0,700,timeout,0 +620050,0,700,timeout,0 +620051,0,700,timeout,0 +620052,0,700,timeout,0 +620053,1,163,success,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,0,700,timeout,0 +620058,0,700,timeout,0 +620059,0,700,timeout,0 +620060,0,700,timeout,0 +620061,0,700,timeout,0 +620062,0,700,timeout,0 +620063,0,700,timeout,0 +620064,1,185,success,0 +620065,1,177,success,0 +620066,0,700,timeout,0 +620067,0,700,timeout,0 +620068,0,700,timeout,0 +620069,0,700,timeout,0 +620070,0,700,timeout,0 +620071,0,700,timeout,0 +620072,0,700,timeout,0 +620073,0,700,timeout,0 +620074,0,700,timeout,0 +620075,0,700,timeout,0 +620076,0,700,timeout,0 +620077,0,700,timeout,0 +620078,0,700,timeout,0 +620079,0,700,timeout,0 +620080,0,700,timeout,0 +620081,0,700,timeout,0 +620082,0,700,timeout,0 +620083,0,700,timeout,0 +620084,0,700,timeout,0 +620085,0,700,timeout,0 +620086,0,700,timeout,0 +620087,0,700,timeout,0 +620088,0,700,timeout,0 +620089,0,700,timeout,0 +620090,0,700,timeout,0 +620091,0,700,timeout,0 +620092,0,700,timeout,0 +620093,0,700,timeout,0 +620094,0,700,timeout,0 +620095,1,179,success,0 +620096,0,700,timeout,0 +620097,1,231,success,0 +620098,0,700,timeout,0 +620099,0,700,timeout,0 diff --git a/policies/reach_target_multi_modal/deepseek1017-s2/policy.py b/policies/reach_target_multi_modal/deepseek1017-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2e92ddeb18a0c2d2ba039384eef3f9b2597b6717 --- /dev/null +++ b/policies/reach_target_multi_modal/deepseek1017-s2/policy.py @@ -0,0 +1,862 @@ +"""Hand-written control policy for touching a red sphere. + +The policy is a deterministic visual-servo controller. It looks for the red +sphere in the head camera, drives the base towards it, then uses an online +image-space Jacobian estimated by small joint probes to bring one hand onto the +sphere. The wrist cameras are used as proximity/contact sensors for the final +approach. No learned components are used. +""" + +import numpy as np +import cv2 + + +# --------------------------------------------------------------------------- +# small helpers +# --------------------------------------------------------------------------- + +def _clip(x, lo, hi): + return float(min(hi, max(lo, x))) + + +def _red_blob(im): + """Return the largest red connected component of an RGB image. + + Returns a dict with cx, cy, area, w, h, r (equivalent radius) or None. + """ + if im is None: + return None + rgb = np.asarray(im, dtype=np.uint8) + if rgb.ndim != 3 or rgb.shape[2] < 3: + return None + r = rgb[..., 0].astype(np.int16) + g = rgb[..., 1].astype(np.int16) + b = rgb[..., 2].astype(np.int16) + # The target is strongly red: red channel dominates both others, and is + # reasonably bright (it can be dark on the shaded side). + m = ((r > 45) & (r > 1.35 * g + 6) & (r > 1.35 * b + 6)) + m = m.astype(np.uint8) + if m.sum() < 6: + return None + # remove isolated speckles + m = cv2.morphologyEx(m, cv2.MORPH_OPEN, np.ones((2, 2), np.uint8)) + n, lab, stats, cent = cv2.connectedComponentsWithStats(m, 8) + if n <= 1: + return None + areas = stats[1:, cv2.CC_STAT_AREA] + k = int(np.argmax(areas)) + 1 + area = float(stats[k, cv2.CC_STAT_AREA]) + if area < 8: + return None + x = float(stats[k, cv2.CC_STAT_LEFT]) + y = float(stats[k, cv2.CC_STAT_TOP]) + w = float(stats[k, cv2.CC_STAT_WIDTH]) + h = float(stats[k, cv2.CC_STAT_HEIGHT]) + cx, cy = cent[k] + return { + "cx": float(cx), + "cy": float(cy), + "area": area, + "w": w, + "h": h, + "r": float(np.sqrt(area / np.pi)), + "x0": x, + "y0": y, + } + + +def _white_components(im): + """Return connected components of the robot's white arms.""" + if im is None: + return [] + rgb = np.asarray(im, dtype=np.uint8) + hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV) + s = hsv[..., 1].astype(np.int16) + v = hsv[..., 2].astype(np.int16) + m = ((s < 62) & (v > 135)).astype(np.uint8) + m = cv2.morphologyEx(m, cv2.MORPH_OPEN, np.ones((2, 2), np.uint8)) + n, lab, stats, cent = cv2.connectedComponentsWithStats(m, 8) + out = [] + for k in range(1, n): + area = int(stats[k, cv2.CC_STAT_AREA]) + if area < 35: + continue + x0 = int(stats[k, cv2.CC_STAT_LEFT]) + y0 = int(stats[k, cv2.CC_STAT_TOP]) + w = int(stats[k, cv2.CC_STAT_WIDTH]) + h = int(stats[k, cv2.CC_STAT_HEIGHT]) + ymax = y0 + h - 1 + # pixels of this component + ys, xs = np.nonzero(lab == k) + ymin = int(ys.min()) + top = xs[ys <= ymin + 1] + tip = (float(np.median(top)), float(ymin)) + bot = xs[ys >= ymax - 1] + anchor = (float(np.median(bot)), float(ymax)) + out.append( + { + "area": area, + "x0": x0, + "y0": y0, + "x1": x0 + w - 1, + "y1": y0 + h - 1, + "tip": tip, + "anchor": anchor, + "cx": float(cent[k][0]), + "cy": float(cent[k][1]), + } + ) + return out + + +def _pick_arm(im, side, prev_tip): + """Pick the white component of one arm and return (tip, anchor, area).""" + comps = _white_components(im) + if not comps: + return None + if side == "L": + # arm must reach the bottom-left shoulder area + cands = [c for c in comps if c["x0"] < 34 and c["y1"] > 62] + if not cands: + cands = [c for c in comps if c["cx"] < 42] + else: + cands = [c for c in comps if c["x1"] > 49 and c["y1"] > 62] + if not cands: + cands = [c for c in comps if c["cx"] > 42] + if not cands: + cands = comps + if prev_tip is not None: + # prefer the component continuing the previous observation + def score(c): + d = (c["tip"][0] - prev_tip[0]) ** 2 + (c["tip"][1] - prev_tip[1]) ** 2 + return d - 0.02 * c["area"] + c = min(cands, key=score) + else: + c = max(cands, key=lambda cc: cc["area"]) + return c["tip"], c["anchor"], c["area"] + + +def _wrist_red(tools, side): + """Detect the red sphere in a wrist camera.""" + try: + cam = "left_wrist" if side == "L" else "right_wrist" + im = tools.image(cam, 84, 84) + return _red_blob(im) + except Exception: + return None + + +# --------------------------------------------------------------------------- +# policy +# --------------------------------------------------------------------------- + +class Policy: + def reset(self, obs, tools): + self.hold0 = np.asarray(tools.hold_action(), dtype=np.float64).reshape(-1).copy() + if self.hold0.size != 20: + a = np.zeros(20, dtype=np.float64) + a[: self.hold0.size] = self.hold0[:20] + self.hold0 = a + self.cmd = self.hold0.copy() + + ld = np.asarray(obs["low_dim_obs"], dtype=np.float64).reshape(-1) + self.qL = ld[0:7].copy() + self.qR = ld[9:16].copy() + self.qmL = self.qL.copy() + self.qmR = self.qR.copy() + # command measured arm poses so there is no jump at reset + self.cmd[4:11] = self.qL + self.cmd[11:18] = self.qR + self.cmd[0:4] = 0.0 + self.cmd[2] = float(self.hold0[2]) + self.cmd[18] = float(self.hold0[18]) + self.cmd[19] = float(self.hold0[19]) + + self.T = int(obs.get("time_limit", 400) or 400) + self.t = 0 + self.phase = "ALIGN" + self.phase_t = 0 + self.ball = None # last head-camera ball + self.ball_miss = 0 + self.prev_tip = {"L": None, "R": None} + self.side = "L" + self.q0 = self.qL.copy() + self.qcmd = self.qL.copy() + self.J = None + self.E = None + self.probe_joints = [] + self.probe_idx = 0 + self.probe_state = "idle" + self.probe_t = 0 + self.p_before = None + self.p_after = None + self.s_before = None + self.s_after = None + self.servo_t = 0 + self.servo_last_e = None + self.servo_stall = 0 + self.servo_conv = 0 + self.servo_stuck = 0 + self.final_t = 0 + self.final_mode = "start" + self.final_creep = 0 + self.final_squat_t = 0 + self.h0 = float(self.cmd[2]) + self.h_target = float(self.cmd[2]) + self.hold_t = 0 + self.hold_creep = 0 + self.wf_prev = 0.0 + self.wf_drop = 0 + self.wf_peak = 0.0 + self.close_t = 0 + self.approach_started = False + self.approach_t = 0 + self.approach_r = None + self.log = [] + + # -- main ------------------------------------------------------------ + def act(self, obs, tools): + try: + return self._act(obs, tools) + except Exception: + # last-resort safe action: hold still + try: + return np.asarray(self.cmd, dtype=np.float64).reshape(-1) + except Exception: + return np.zeros(20, dtype=np.float64) + + def _act(self, obs, tools): + self.t += 1 + self.phase_t += 1 + ld_now = np.asarray(obs.get("low_dim_obs", np.zeros(50)), dtype=np.float64) + self.qmL = ld_now[0:7].copy() + self.qmR = ld_now[9:16].copy() + self.cmd[0] = 0.0 + self.cmd[1] = 0.0 + self.cmd[3] = 0.0 + + # refresh head perception + head = None + try: + head = tools.image("head", 84, 84) + except Exception: + head = None + if head is not None: + b = _red_blob(head) + if b is not None: + self.ball = b + self.ball_miss = 0 + else: + self.ball_miss += 1 + + if self.phase == "ALIGN": + self._phase_align(obs, tools, head) + elif self.phase == "SEARCH": + self._phase_search(obs, tools, head) + elif self.phase == "SETTLE": + self._phase_settle(obs, tools, head) + elif self.phase == "PREP": + self._phase_prep(obs, tools, head) + elif self.phase == "PROBE": + self._phase_probe(obs, tools, head) + elif self.phase == "SERVO": + self._phase_servo(obs, tools, head) + elif self.phase == "FINAL": + self._phase_final(obs, tools, head) + else: + self._phase_hold(obs, tools, head) + + return self._action() + + def _go(self, phase): + self.phase = phase + self.phase_t = 0 + + def _action(self): + a = np.asarray(self.cmd, dtype=np.float64).reshape(-1).copy() + a = np.nan_to_num(a, nan=0.0, posinf=0.0, neginf=0.0) + a[0] = _clip(a[0], -1.0, 1.0) + a[1] = _clip(a[1], -1.0, 1.0) + a[2] = _clip(a[2], 0.4, 1.0) + a[3] = _clip(a[3], -1.0, 1.0) + a[4:18] = np.clip(a[4:18], -3.0, 3.0) + a[18] = _clip(a[18], 0.0, 1.0) + a[19] = _clip(a[19], 0.0, 1.0) + return a + + # -- phase helpers --------------------------------------------------- + def _set_arm_cmd(self, side, q): + if side == "L": + self.cmd[4:11] = q + else: + self.cmd[11:18] = q + + def _set_height_toward(self, target, rate=0.02): + h = self.cmd[2] + if h < target: + h = min(target, h + rate) + else: + h = max(target, h - rate) + self.cmd[2] = h + + def _wrist_best(self, tools): + """Return (name, blob) for the wrist camera with the most red.""" + best = (None, None) + for name in (self.side, "R" if self.side == "L" else "L"): + b = _wrist_red(tools, name) + if b is not None and (best[1] is None or b["area"] > best[1]["area"]): + best = (name, b) + return best + + def _wrist_cur(self, tools): + """Return the sphere blob in the wrist camera of the active arm.""" + b = _wrist_red(tools, self.side) + return (self.side, b) if b is not None else (self.side, None) + + # -- ALIGN: find sphere, steer base to it, approach to reference size -- + def _phase_align(self, obs, tools, head): + b = self.ball + # if the ball is already filling a wrist view, go straight to final + wn, wb = self._wrist_best(tools) + if wb is not None and wb["area"] > 500: + self.side = wn + self._go("FINAL") + return + if b is None: + if self.ball_miss > 10: + self._go("SEARCH") + return + if self.ball_miss > 15: + self.cmd[0] = 0.0 + self._go("SEARCH") + return + + du = b["cx"] - 45.0 + wz = _clip(-0.020 * du, -0.55, 0.55) + self.cmd[3] = wz + + r = b["r"] + if abs(du) > 28.0: + # turn in place first + vx = 0.0 + elif abs(du) > 12.0: + vx = 0.16 + elif r < 5.5: + vx = 0.35 + elif r < 6.90: + vx = 0.28 + else: + vx = 0.0 + self.cmd[0] = vx + + # detect being blocked (e.g. by the table edge): if walking does not + # make the sphere grow after a while, stop pushing and reach instead + if vx > 0.02: + if self.approach_r is None: + self.approach_r = r + self.approach_t = 0 + else: + self.approach_t += 1 + else: + self.approach_r = None + self.approach_t = 0 + + # stop criteria: aligned, close enough, or too close / timed out + aligned = abs(du) < 6.0 + close = r >= 6.75 + too_close = r > 11.0 + blocked = self.approach_t > 28 and r < self.approach_r + 0.10 + if (aligned and close) or too_close or blocked: + self.cmd[0] = 0.0 + self.cmd[3] = 0.0 + # if we are already centered, skip the extra settle wait + if aligned: + self._go("PREP") + else: + self._go("SETTLE") + return + if self.phase_t > max(50, int(0.42 * self.T)): + self.cmd[0] = 0.0 + self.cmd[3] = 0.0 + self._go("SETTLE") + + # -- SEARCH: rotate until the sphere is visible ---------------------- + def _phase_search(self, obs, tools, head): + wn, wb = self._wrist_best(tools) + if wb is not None and wb["area"] > 220: + self.side = wn + self._go("FINAL") + return + if self.ball is not None and self.ball_miss == 0: + self._go("ALIGN") + return + # sweep right, then left, then right again + period = max(25, min(60, self.T // 8)) + k = (self.phase_t // period) % 2 + self.cmd[3] = 0.55 if k == 0 else -0.55 + if self.phase_t > max(80, int(0.28 * self.T)): + self._go("SETTLE") + + # -- SETTLE: stop and fine-align in place ---------------------------- + def _phase_settle(self, obs, tools, head): + b = self.ball + if self.phase_t < 12 and b is not None: + du = b["cx"] - 45.0 + if abs(du) > 5.0: + self.cmd[3] = _clip(-0.014 * du, -0.25, 0.25) + else: + self.cmd[3] = 0.0 + return + self.cmd[3] = 0.0 + self._go("PREP") + + # -- PREP: choose the arm and start the probe ------------------------ + def _phase_prep(self, obs, tools, head): + b = self.ball + self.side = "L" + if b is not None and b["cx"] > 56.0: + self.side = "R" + ld = np.asarray(obs["low_dim_obs"], dtype=np.float64) + if self.side == "L": + self.q0 = ld[0:7].copy() + self.qcmd = self.q0.copy() + else: + self.q0 = ld[9:16].copy() + self.qcmd = self.q0.copy() + # fresh measured pose + self._set_arm_cmd(self.side, self.qcmd) + + n_budget = self.T - self.t + if n_budget > 330: + self.probe_joints = [0, 1, 2, 3] + elif n_budget > 130: + self.probe_joints = [0, 1, 3] + else: + self.probe_joints = [] + self.probe_idx = 0 + self.probe_state = "before" + self.probe_t = 0 + self.p_before = None + self.p_after = None + self.J = np.zeros((2, 4), dtype=np.float64) + self.E = np.zeros(4, dtype=np.float64) + if not self.probe_joints: + self._finish_probe() + else: + self._go("PROBE") + + def _arm_tip(self, head): + if head is None: + return None + try: + res = _pick_arm(head, self.side, self.prev_tip[self.side]) + except Exception: + return None + if res is None: + return None + tip, anchor, area = res + self.prev_tip[self.side] = tip + return tip, anchor + + def _measured_arm(self, obs): + ld = np.asarray(obs["low_dim_obs"], dtype=np.float64) + if self.side == "L": + return ld[0:7].copy() + return ld[9:16].copy() + + def _servo_step(self, head, gain=0.45, overshoot=0.0): + """One small image-space step of the hand towards the sphere.""" + if head is None or self.ball is None or self.J is None: + return 0.0 + tp = self._arm_tip(head) + if tp is None: + return 0.0 + tip, anchor = tp + b = self.ball + ux = b["cx"] - tip[0] + uy = b["cy"] - tip[1] + n = float(np.hypot(ux, uy)) + if n < 1e-3: + return n + ux /= n + uy /= n + e = np.array( + [b["cx"] + overshoot * ux - tip[0], b["cy"] + overshoot * uy - tip[1]], + dtype=np.float64, + ) + try: + dq = self.J.T @ np.linalg.solve( + self.J @ self.J.T + 40.0 * np.eye(2), e + ) + except Exception: + return n + dq = np.nan_to_num(dq, nan=0.0, posinf=0.0, neginf=0.0) + dn = float(np.max(np.abs(dq))) + if dn > 0.14: + dq *= 0.14 / dn + dq *= gain + if self.E is not None and n > 4.0: + for j in range(4): + if abs(self.E[j]) > 0.3: + dq[j] += 0.012 * np.sign(self.E[j]) + q = self.qcmd.copy() + q[0:4] = np.clip(q[0:4] + dq, self.q0[0:4] - 1.4, self.q0[0:4] + 1.4) + qm = self.qmL if self.side == "L" else self.qmR + q[0:4] = np.clip(q[0:4], qm[0:4] - 0.9, qm[0:4] + 0.9) + self.qcmd = np.clip(q, -3.0, 3.0) + self._set_arm_cmd(self.side, self.qcmd) + return n + + def _phase_probe(self, obs, tools, head): + j = self.probe_joints[self.probe_idx] + delta = 0.30 + meas = self._measured_arm(obs) + + if self.probe_state == "before": + self.qcmd = self.q0.copy() + self._set_arm_cmd(self.side, self.qcmd) + self.probe_t += 1 + close = abs(meas[j] - self.q0[j]) < 0.08 + if self.probe_t < 2 or (not close and self.probe_t < 6): + return + tp = self._arm_tip(head) + bb = self.ball + self.p_before = (tp, None if bb is None else (bb["cx"], bb["cy"])) + self.probe_t = 0 + self.probe_state = "move" + return + + if self.probe_state == "move": + q = self.q0.copy() + q[j] = q[j] + delta + self.qcmd = q + self._set_arm_cmd(self.side, q) + self.probe_t += 1 + close = abs(meas[j] - q[j]) < 0.09 + if self.probe_t < 3 or (not close and self.probe_t < 11): + return + tp = self._arm_tip(head) + bb = self.ball + self.p_after = (tp, None if bb is None else (bb["cx"], bb["cy"])) + self._store_probe(j, delta) + self.probe_t = 0 + self.probe_state = "back" + return + + # back: return to neutral + self.qcmd = self.q0.copy() + self._set_arm_cmd(self.side, self.qcmd) + self.probe_t += 1 + close = abs(meas[j] - self.q0[j]) < 0.08 + if self.probe_t < 2 or (not close and self.probe_t < 6): + return + self.probe_idx += 1 + self.probe_t = 0 + self.probe_state = "before" + if self.probe_idx >= len(self.probe_joints): + self._finish_probe() + + def _store_probe(self, j, delta): + if self.p_before is None or self.p_after is None: + return + (tb, ab), bb = self.p_before + (ta, aa), ba = self.p_after + if tb is None or ta is None: + return + dx = ta[0] - tb[0] + dy = ta[1] - tb[1] + # use the tip relative to the sphere when both are visible: this + # cancels any common motion of the head camera (torso balance) + if bb is not None and ba is not None: + dx = (ta[0] - ba[0]) - (tb[0] - bb[0]) + dy = (ta[1] - ba[1]) - (tb[1] - bb[1]) + self.J[0, j] = dx / delta + self.J[1, j] = dy / delta + sb = np.hypot(tb[0] - ab[0], tb[1] - ab[1]) + sa = np.hypot(ta[0] - aa[0], ta[1] - aa[1]) + self.E[j] = (sa - sb) / delta + + def _finish_probe(self): + # fill any unprobed column with a small regularization toward zero + J = self.J + # if the estimated Jacobian is degenerate, add tiny diagonal terms + if not np.all(np.isfinite(J)): + J = np.zeros((2, 4)) + # rank check + try: + rank = np.linalg.matrix_rank(J, tol=1e-6) + except Exception: + rank = 0 + if rank < 2: + # fallback: assume pitch moves mostly vertically, roll mostly + # horizontally. This is only a last resort. + J = J.copy() + if abs(J[0, 1]) + abs(J[1, 0]) < 1e-6: + J[0, 1] += 4.0 + J[1, 0] += 4.0 + self.J = J + self.servo_t = 0 + self.servo_stall = 0 + self.servo_conv = 0 + self.servo_last_e = None + self._go("SERVO") + + # -- SERVO: image-space hand-tip Jacobian control -------------------- + def _phase_servo(self, obs, tools, head): + b = self.ball + # wrist proximity wins immediately + wn, wb = self._wrist_cur(tools) + if wb is not None and wb["area"] > 450: + self.side = wn + self._go("FINAL") + return + + max_servo = max(40, int(0.30 * self.T)) + if self.phase_t > max_servo: + self._go("FINAL") + return + + if b is None: + # ball hidden behind the hand: likely close; give it a few steps + if self.ball_miss > 12 or self.phase_t > 0.6 * max_servo: + self._go("FINAL") + else: + self._set_arm_cmd(self.side, self.qcmd) + return + + # update every 3 steps + if self.phase_t % 3 != 0: + self._set_arm_cmd(self.side, self.qcmd) + return + + tp = self._arm_tip(head) + if tp is None: + self._set_arm_cmd(self.side, self.qcmd) + return + tip, anchor = tp + e = np.array([b["cx"] - tip[0], b["cy"] - tip[1]], dtype=np.float64) + en = float(np.hypot(e[0], e[1])) + # aim a few pixels past the sphere centre: the hand has thickness and + # the arm has to extend (not just line up in the image) + if en > 1e-3: + e = e + 3.0 * e / en + + if en < 4.0: + self.servo_conv += 1 + if self.servo_conv >= 2: + self._go("FINAL") + return + else: + self.servo_conv = 0 + + if self.servo_last_e is None: + self.servo_last_e = en + self.servo_stall = 0 + else: + if en > self.servo_last_e - 0.4: + self.servo_stall += 1 + else: + self.servo_stall = max(0, self.servo_stall - 1) + self.servo_last_e = en + + J = self.J + lam = 40.0 + try: + A = J @ J.T + lam * np.eye(2) + dq = J.T @ np.linalg.solve(A, e) + except Exception: + dq = np.zeros(4) + dq = np.nan_to_num(dq, nan=0.0, posinf=0.0, neginf=0.0) + dn = float(np.max(np.abs(dq))) + if dn > 0.14: + dq *= 0.14 / dn + dq *= 0.55 + + # small push towards arm extension in the null space (helps depth) + if en > 5.0: + for j in range(4): + if abs(self.E[j]) > 0.3: + dq[j] += 0.016 * np.sign(self.E[j]) + + # if stalled, try a different direction / larger step + if self.servo_stall >= 4: + self.servo_stall = 0 + self.servo_stuck += 1 + dq = dq * 1.8 + self.servo_last_e = None + if self.servo_stuck >= 3: + self._go("FINAL") + return + + q = self.qcmd.copy() + q[0:4] = q[0:4] + dq + # keep within a safe envelope around the measured neutral pose + q[0:4] = np.clip(q[0:4], self.q0[0:4] - 1.3, self.q0[0:4] + 1.3) + # anti-windup: never lead the physical arm by more than ~0.9 rad + qm = self.qmL if self.side == "L" else self.qmR + q[0:4] = np.clip(q[0:4], qm[0:4] - 0.9, qm[0:4] + 0.9) + # broad joint sanity limits + q = np.clip(q, -3.0, 3.0) + self.qcmd = q + self._set_arm_cmd(self.side, q) + self.servo_t += 1 + + # -- FINAL: close the last gap with wrist feedback / creep / squat --- + def _phase_final(self, obs, tools, head): + self.final_t += 1 + wn, wb = self._wrist_cur(tools) + wf = 0.0 if wb is None else wb["area"] / (84.0 * 84.0) + + if wf > 0.28: + self.wf_peak = max(self.wf_peak, wf) + self._go("HOLD") + return + + # the sphere is visible in a wrist camera: steer/creep towards it + if wb is not None and wb["area"] > 15: + self.wf_peak = max(self.wf_peak, wf) + # while still far, use the vertical position of the sphere in the + # wrist view to adjust the body height (lower if the sphere is low + # in view, raise if it is high) + if self.wf_peak < 0.20 and wf < 0.15: + if wb["cy"] > 52.0: + self._set_height_toward(max(0.48, self.cmd[2] - 0.010), rate=0.010) + elif wb["cy"] < 34.0: + self._set_height_toward(min(0.78, self.cmd[2] + 0.010), rate=0.010) + # use the head camera for steering (its orientation is known); + # the wrist is the proximity sensor + if self.ball is not None and self.ball_miss < 10: + self.cmd[3] = _clip(-0.012 * (self.ball["cx"] - 45.0), -0.30, 0.30) + else: + self.cmd[3] = 0.0 + if wf < 0.20: + self._servo_step(head, gain=0.35, overshoot=2.0) + # a large drop after the sphere was close means the hand has + # reached/passed it: stop creeping and let contact settle + if ( + self.wf_peak > 0.22 + and wf < self.wf_prev - 0.05 + and wf > 0.01 + ): + self.wf_drop += 1 + else: + self.wf_drop = 0 + self.wf_prev = wf + if ( + wf < 0.35 + and self.wf_drop < 2 + and self.final_creep < 60 + ): + self.cmd[0] = 0.08 + self.final_creep += 1 + else: + self.cmd[0] = 0.0 + self._set_arm_cmd(self.side, self.qcmd) + return + + # no wrist view + if self.final_mode == "start": + self.final_mode = "push" + self.final_t = 0 + return + + if self.final_mode == "push": + b = self.ball + if b is not None and self.ball_miss < 10: + self._servo_step(head, gain=0.45, overshoot=2.5) + self.cmd[0] = 0.06 + if self.final_t > 16: + self.final_mode = "creep" + self.final_t = 0 + self.final_creep = 0 + return + + if self.final_mode == "creep": + self._set_height_toward(min(self.h0, 0.74), rate=0.015) + b = self.ball + if b is not None: + self.cmd[3] = _clip(-0.012 * (b["cx"] - 45.0), -0.25, 0.25) + self.cmd[0] = 0.10 + self.final_creep += 1 + self._set_arm_cmd(self.side, self.qcmd) + stop = False + if b is not None and b["r"] > 10.5: + stop = True + if self.ball_miss > 12: + stop = True + if self.final_creep > 32: + stop = True + if stop: + self.final_mode = "squat" + self.final_t = 0 + self.final_squat_t = 0 + self.cmd[0] = 0.0 + self.cmd[3] = 0.0 + return + + if self.final_mode == "squat": + self.cmd[0] = 0.0 + self.cmd[3] = 0.0 + self._set_height_toward(0.47, rate=0.012) + self.final_squat_t += 1 + if self.ball is not None and self.ball_miss < 8: + self._servo_step(head, gain=0.30, overshoot=1.0) + self._set_arm_cmd(self.side, self.qcmd) + if self.cmd[2] <= 0.48 or self.final_squat_t > 34: + self.final_mode = "wiggle" + self.final_t = 0 + return + + if self.final_mode == "wiggle": + self.cmd[0] = 0.0 + self.cmd[3] = 0.0 + q = self.qcmd.copy() + seq = [0.0, 0.30, -0.30, 0.18, -0.18] + a = seq[(self.final_t // 6) % len(seq)] + j = 0 + if self.J is not None: + jj = int(np.argmax(np.abs(self.J[1, :4]))) + if abs(self.J[1, jj]) > 0.5: + j = jj + q[j] += a + q[3] += 0.12 * np.sin(0.5 * self.final_t) + q = np.clip(q, self.q0 - 1.4, self.q0 + 1.4) + self._set_arm_cmd(self.side, q) + if self.final_t > 40: + self._go("HOLD") + return + + self._go("HOLD") + + # -- HOLD: keep the pose, watch for contact, optionally press --------- + def _phase_hold(self, obs, tools, head): + self.hold_t += 1 + self.cmd[0] = 0.0 + self.cmd[1] = 0.0 + self.cmd[3] = 0.0 + self._set_arm_cmd(self.side, self.qcmd) + + wn, wb = self._wrist_cur(tools) + wf = 0.0 if wb is None else wb["area"] / (84.0 * 84.0) + + # gentle final pressure: creep a little while the sphere is close but + # not yet filling the wrist view + b = self.ball + self.wf_peak = max(self.wf_peak, wf) + settled = self.wf_peak > 0.22 and wf < self.wf_peak - 0.05 + if wf < 0.35 and self.hold_creep < 20 and not settled: + if b is not None and self.ball_miss < 10 and b["r"] < 10.5: + self.cmd[0] = 0.08 + self.hold_creep += 1 + elif self.ball_miss >= 10 and wf < 0.02: + self.cmd[0] = 0.06 + self.hold_creep += 1 + + # micro adjustment towards the sphere in the head view + if ( + wf < 0.35 + and self.hold_t % 6 == 0 + and b is not None + and self.ball_miss < 8 + ): + self._servo_step(head, gain=0.25, overshoot=1.0) diff --git a/policies/reach_target_multi_modal/deepseek1017-s3/episodes.csv b/policies/reach_target_multi_modal/deepseek1017-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..1e2f702858dadf49261d66bdeb029105135e9b38 --- /dev/null +++ b/policies/reach_target_multi_modal/deepseek1017-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,700,timeout,0 +620001,0,700,timeout,0 +620002,0,700,timeout,0 +620003,0,700,timeout,0 +620004,0,700,timeout,0 +620005,0,700,timeout,0 +620006,0,700,timeout,0 +620007,0,700,timeout,0 +620008,0,700,timeout,0 +620009,0,700,timeout,0 +620010,0,700,timeout,0 +620011,0,700,timeout,0 +620012,0,700,timeout,0 +620013,0,700,timeout,0 +620014,0,700,timeout,0 +620015,0,700,timeout,0 +620016,0,700,timeout,0 +620017,0,700,timeout,0 +620018,0,700,timeout,0 +620019,0,700,timeout,0 +620020,0,700,timeout,0 +620021,0,700,timeout,0 +620022,0,700,timeout,0 +620023,0,700,timeout,0 +620024,0,700,timeout,0 +620025,0,700,timeout,0 +620026,0,700,timeout,0 +620027,0,700,timeout,0 +620028,0,700,timeout,0 +620029,0,700,timeout,0 +620030,0,700,timeout,0 +620031,0,700,timeout,0 +620032,0,700,timeout,0 +620033,0,700,timeout,0 +620034,0,700,timeout,0 +620035,0,700,timeout,0 +620036,0,700,timeout,0 +620037,0,700,timeout,0 +620038,0,700,timeout,0 +620039,0,700,timeout,0 +620040,0,700,timeout,0 +620041,0,700,timeout,0 +620042,0,700,timeout,0 +620043,0,700,timeout,0 +620044,0,700,timeout,0 +620045,0,700,timeout,0 +620046,0,700,timeout,0 +620047,0,700,timeout,0 +620048,0,700,timeout,0 +620049,0,700,timeout,0 +620050,0,700,timeout,0 +620051,0,700,timeout,0 +620052,0,700,timeout,0 +620053,0,700,timeout,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,0,700,timeout,0 +620058,1,493,success,0 +620059,0,700,timeout,0 +620060,0,700,timeout,0 +620061,0,700,timeout,0 +620062,0,700,timeout,0 +620063,0,700,timeout,0 +620064,0,700,timeout,0 +620065,0,700,timeout,0 +620066,0,700,timeout,0 +620067,0,700,timeout,0 +620068,0,700,timeout,0 +620069,0,700,timeout,0 +620070,0,700,timeout,0 +620071,0,700,timeout,0 +620072,0,700,timeout,0 +620073,0,700,timeout,0 +620074,0,700,timeout,0 +620075,0,700,timeout,0 +620076,0,700,timeout,0 +620077,0,700,timeout,0 +620078,0,700,timeout,0 +620079,0,700,timeout,0 +620080,0,700,timeout,0 +620081,0,700,timeout,0 +620082,0,700,timeout,0 +620083,0,700,timeout,0 +620084,0,700,timeout,0 +620085,0,700,timeout,0 +620086,0,700,timeout,0 +620087,0,700,timeout,0 +620088,0,700,timeout,0 +620089,0,700,timeout,0 +620090,0,700,timeout,0 +620091,0,700,timeout,0 +620092,0,700,timeout,0 +620093,0,700,timeout,0 +620094,0,700,timeout,0 +620095,0,700,timeout,0 +620096,0,700,timeout,0 +620097,0,700,timeout,0 +620098,0,700,timeout,0 +620099,0,700,timeout,0 diff --git a/policies/reach_target_multi_modal/deepseek1017-s3/policy.py b/policies/reach_target_multi_modal/deepseek1017-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..e79f0cb41eba6e169e1b89d905f6bffc3713e792 --- /dev/null +++ b/policies/reach_target_multi_modal/deepseek1017-s3/policy.py @@ -0,0 +1,814 @@ +"""Hand-written visual-servo policy for touching a red sphere with a hand. + +The policy never receives object positions. It finds the red sphere in the +robot cameras, turns the body so the sphere is in front, walks towards it at a +modest speed, and aligns one hand with the sphere in the head image. The local +mapping from the two shoulder joints to the hand's image position is measured +online with short deterministic probes, so no learned model is used. + +Everything is closed-loop on the robot's own head and wrist cameras and on the +body state. There is no wall-clock use and no randomness. +""" + +import numpy as np +import cv2 + +CENTER = 42.0 # principal point of the 84x84 cameras +LIMIT_PITCH = (-2.75, 1.55) +LIMIT_ROLL = (-1.55, 1.55) +LIMIT_ELBOW = (-1.00, 2.05) + + +# ---------------------------------------------------------------------------- +# perception helpers +# ---------------------------------------------------------------------------- +def detect_red(img): + """Return the red sphere in one 84x84 RGB image, or None. + + Returns a dict with the (area-weighted) centroid, total area and bounding + box. All sufficiently large red blobs are summed, which keeps the sphere + detectable while the hand occludes part of it. + """ + a = img.astype(np.int16) + r, g, b = a[..., 0], a[..., 1], a[..., 2] + m = (r > 50) & (r > 1.35 * g + 8) & (r > 1.35 * b + 8) + m = m.astype(np.uint8) + n, lab, stats, cents = cv2.connectedComponentsWithStats(m, 8) + total = 0.0 + sx = sy = 0.0 + x0 = y0 = 10 ** 6 + x1 = y1 = -1 + for i in range(1, n): + area = float(stats[i, cv2.CC_STAT_AREA]) + if area < 5.0: + continue + cx, cy = cents[i] + total += area + sx += cx * area + sy += cy * area + x = int(stats[i, cv2.CC_STAT_LEFT]) + y = int(stats[i, cv2.CC_STAT_TOP]) + w = int(stats[i, cv2.CC_STAT_WIDTH]) + h = int(stats[i, cv2.CC_STAT_HEIGHT]) + x0, y0 = min(x0, x), min(y0, y) + x1, y1 = max(x1, x + w - 1), max(y1, y + h - 1) + if total < 5.0: + return None + return { + "cx": sx / total, + "cy": sy / total, + "area": total, + "x0": x0, + "y0": y0, + "x1": x1, + "y1": y1, + } + + +def white_mask(img, thr=168): + """Binary mask of the bright (white) robot limbs.""" + mn = img.min(axis=2) + m = (mn > thr).astype(np.uint8) + # close single-pixel compression gaps between the arm segments + m = cv2.morphologyEx(m, cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8)) + return m + + +def arm_tip(img, side="L"): + """Find the far end of one forearm in the head image. + + The left arm enters the head view from the left border and the right arm + from the right border. The principal axis of that bright component gives + the direction from the shoulder to the hand; the extreme point is the + wrist/hand. + """ + m = white_mask(img) + n, lab, stats, cents = cv2.connectedComponentsWithStats(m, 8) + best = None + for i in range(1, n): + area = int(stats[i, cv2.CC_STAT_AREA]) + if area < 45: + continue + x = int(stats[i, cv2.CC_STAT_LEFT]) + y = int(stats[i, cv2.CC_STAT_TOP]) + w = int(stats[i, cv2.CC_STAT_WIDTH]) + h = int(stats[i, cv2.CC_STAT_HEIGHT]) + if side == "L": + touch = (x <= 1) or (x <= 8 and y < 66 and area > 110 and x + w < 62) + else: + touch = (x + w >= 83) or (x + w >= 76 and y < 66 and area > 110 and x > 22) + if not touch: + continue + if best is None or area > best[0]: + best = (area, i) + if best is None: + # When the arm is raised it can detach from the image border. The + # raised limb is then the highest bright component on its side of the + # image (the feet/torso stay near the bottom). + cand = None + for i in range(1, n): + area = int(stats[i, cv2.CC_STAT_AREA]) + if area < 80: + continue + x = int(stats[i, cv2.CC_STAT_LEFT]) + y = int(stats[i, cv2.CC_STAT_TOP]) + w = int(stats[i, cv2.CC_STAT_WIDTH]) + if y > 64: + continue + cx = float(cents[i][0]) + if side == "L" and not (x + w < 62 and cx < 42.0): + continue + if side == "R" and not (x > 22 and cx > 42.0): + continue + if cand is None or y < cand[0] or (y == cand[0] and area > cand[1]): + cand = (y, area, i) + if cand is None: + return None + best = (cand[1], cand[2]) + i = best[1] + ys, xs = np.nonzero(lab == i) + if len(xs) < 20: + return None + pts = np.column_stack([xs, ys]).astype(np.float64) + mean = pts.mean(axis=0) + anchor = np.array([0.0, 84.0]) if side == "L" else np.array([83.0, 84.0]) + # principal direction of the limb + try: + _, _, vt = np.linalg.svd(pts - mean, full_matrices=False) + v = vt[0] + except np.linalg.LinAlgError: + v = mean - anchor + if np.dot(v, mean - anchor) < 0: + v = -v + proj = (pts - anchor) @ v + tip = pts[int(np.argmax(proj))] + return float(tip[0]), float(tip[1]) + + +# ---------------------------------------------------------------------------- +# policy +# ---------------------------------------------------------------------------- +class Policy: + """Visual-servo reach policy for the red-sphere task.""" + + def __init__(self): + self.state = "init" + self.t = 0 + self.limit = 600 + self.fast = False + self.hand = "L" + self.q = [None, None] # commanded arm targets, left/right + self.hold = None + self.height = 0.74 + self.grip = [0.0, 0.0] + self.area_ref = None + self.wrist_max = 0.0 + self.head_area_at_wrist = None + self.attempt = 0 + self.frames_missing = 0 + self.transitions = [] + + # calibration + self.J = None + self.cal_q0 = None + self.cal_obs0 = None + self.cal_y0 = None + self.cal_y = [None, None] + self.cal_dq = [0.0, 0.0] + self.cal_phase = 0 + self.cal_wait = 0 + self.cal_delta = 0.20 + + # servo / search bookkeeping + self.servo_wait = 0 + self.align_count = 0 + self.stall = 0 + self.best_err = 1e9 + self.no_improve = 0 + self.state_steps = 0 + self.search_center = None + self.search_k = 0 + self.hold_steps = 0 + self.wr_area = 0.0 + self.wr_c = (CENTER, CENTER) + self.last_tip = None + self.recal = 0 + self.fell = False + + # -- small utilities ----------------------------------------------------- + def _go(self, state): + if state != self.state: + self.transitions.append((self.t, self.state, state)) + self.state = state + self.state_steps = 0 + + def _arm_index(self): + return 0 if self.hand == "L" else 1 + + def _wrist_name(self): + return "left_wrist" if self.hand == "L" else "right_wrist" + + def _q(self): + return self.q[self._arm_index()] + + def _obs_q(self, obs): + lo = obs["low_dim_obs"] + if self.hand == "L": + return np.asarray(lo[0:7], dtype=np.float64) + return np.asarray(lo[9:16], dtype=np.float64) + + def _action(self): + """Compose the 20-float action from the current targets.""" + raw = np.asarray(self.hold, dtype=np.float32).copy() + raw[0] = 0.0 + raw[1] = 0.0 + raw[2] = float(self.height) + raw[3] = 0.0 + for side, i0 in (("L", 4), ("R", 11)): + k = 0 if side == "L" else 1 + qi = self.q[k] + if qi is None: + continue + aq = self.applied_q[k] + d = np.clip(qi - aq, -0.075, 0.075) + aq += d + raw[i0:i0 + 7] = aq.astype(np.float32) + raw[18] = self.grip[0] + raw[19] = self.grip[1] + return raw + + def _set_base(self, vx=0.0, vy=0.0, wz=0.0): + self._base = (float(vx), float(vy), float(wz)) + + def _finish_action(self): + raw = self._action() + vx, vy, wz = self._base + raw[0], raw[1], raw[3] = vx, vy, wz + return raw + + def _clip_q(self, hand): + q = self.q[0 if hand == "L" else 1] + q[0] = min(max(q[0], LIMIT_PITCH[0]), LIMIT_PITCH[1]) + q[1] = min(max(q[1], LIMIT_ROLL[0]), LIMIT_ROLL[1]) + q[3] = min(max(q[3], LIMIT_ELBOW[0]), LIMIT_ELBOW[1]) + return q + + # -- episode start ------------------------------------------------------- + def reset(self, obs, tools): + self.__init__() + self.t = int(obs.get("t", 0)) + self.limit = int(obs.get("time_limit", 600) or 600) + self.fast = self.limit <= 260 + self.hold = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.height = float(self.hold[2]) + if not (0.40 <= self.height <= 1.0): + self.height = 0.74 + self.q = [ + np.asarray(self.hold[4:11], dtype=np.float64).copy(), + np.asarray(self.hold[11:18], dtype=np.float64).copy(), + ] + self.grip = [float(self.hold[18]), float(self.hold[19])] + self.applied_q = [self.q[0].copy(), self.q[1].copy()] + self.last_tip = None + self.tip_missing = 0 + self._base = (0.0, 0.0, 0.0) + + # -- one control step ---------------------------------------------------- + def act(self, obs, tools): + self.t = int(obs.get("t", self.t + 1)) + self._base = (0.0, 0.0, 0.0) + + if bool(obs.get("fell", False)): + self.fell = True + if self.state != "hold": + self._go("hold") + return self._finish_action() + + # leave enough time to keep the contact latched for one second + if self.state != "hold" and (self.limit - self.t) < 55: + self._go("hold") + + # cameras + head = None + try: + head = tools.image("head", 84, 84) + except Exception: + head = None + sphere = detect_red(head) if head is not None else None + wr = None + try: + wr = tools.image(self._wrist_name(), 84, 84) + except Exception: + wr = None + wrist = detect_red(wr) if wr is not None else None + if wrist is not None: + self.wr_area = wrist["area"] + self.wr_c = (wrist["cx"], wrist["cy"]) + self.wrist_max = max(self.wrist_max, self.wr_area) + else: + self.wr_area = 0.0 + + tip = arm_tip(head, self.hand) if head is not None else None + if tip is not None: + self.last_tip = tip + self.tip_missing = 0 + else: + self.tip_missing += 1 + if self.tip_missing > 3: + self.last_tip = None + + if sphere is not None: + self.frames_missing = 0 + if self.area_ref is None: + self.area_ref = sphere["area"] + if (self.head_area_at_wrist is None and wrist is not None + and wrist["area"] > 20.0 and self.state != "calib"): + self.head_area_at_wrist = sphere["area"] + else: + self.frames_missing += 1 + + # always keep the two arms rate-limited towards their targets + self._base = (0.0, 0.0, 0.0) + if self.state == "init": + self._state_init(obs, sphere, wrist) + elif self.state == "scan": + self._state_scan(obs, sphere, wrist) + elif self.state == "yaw": + self._state_yaw(obs, sphere, wrist) + elif self.state == "calib": + self._state_calib(obs, sphere, wrist) + elif self.state == "servo": + self._state_servo(obs, sphere, wrist) + elif self.state == "search": + self._state_search(obs, sphere, wrist) + elif self.state == "wrist": + self._state_wrist(obs, sphere, wrist) + elif self.state == "blind": + self._state_blind(obs, sphere, wrist) + else: + self._state_hold(obs, sphere, wrist) + + self.state_steps += 1 + return self._finish_action() + + # -- states -------------------------------------------------------------- + def _state_init(self, obs, sphere, wrist): + self._set_base() + if self.state_steps >= (1 if self.fast else 4): + if sphere is not None: + self.area_ref = sphere["area"] + self._go("yaw") + elif wrist is not None and wrist["area"] > 25: + self._go("wrist") + else: + self._go("scan") + + def _state_scan(self, obs, sphere, wrist): + # sweep a little over +/- 70 degrees; if the sphere is still not in + # view after that, the arm sweep is a better use of the remaining time + if self.state_steps < 80: + self._set_base(wz=0.80) + else: + self._set_base(wz=-0.80) + if sphere is not None: + self.area_ref = sphere["area"] + self._go("yaw") + elif wrist is not None and wrist["area"] > 25: + self._go("wrist") + elif self.state_steps > 240: + self._go("blind") + + def _state_yaw(self, obs, sphere, wrist): + if sphere is None: + if wrist is not None and wrist["area"] > 20: + self._go("wrist") + elif self.frames_missing > 12: + self._go("scan") + return + err = sphere["cx"] - CENTER + if abs(err) > 3.0: + wz = float(np.clip(-0.030 * err, -0.35, 0.35)) + if abs(wz) < 0.065: + wz = 0.065 if wz > 0 else -0.065 + self._set_base(wz=wz) + else: + # while the sphere is in the middle of the view its apparent area + # is a fair reference for the "far away" size + self.area_ref = max(self.area_ref or 0.0, sphere["area"]) + wait = 2 if self.fast else 5 + if (abs(err) < 4.0 and self.state_steps > wait) or self.state_steps > 28: + self.area_ref = max(self.area_ref or 0.0, sphere["area"]) + self._start_calib(obs) + + def _start_calib(self, obs): + q = self._q() + self.cal_q0 = q.copy() + self.cal_obs0 = self._obs_q(obs) + self.cal_phase = 0 + self.cal_wait = 2 if self.fast else 3 + self.cal_y0 = None + self.cal_y = [None, None] + self.cal_dq = [0.0, 0.0] + self.J = None + self._go("calib") + + def _state_calib(self, obs, sphere, wrist): + q = self._q() + if self.state_steps > 80: + # something went wrong; go to the safe blind sweep + q[:] = self.cal_q0 + self._go("blind") + return + if sphere is None: + self.frames_missing += 1 + if wrist is not None and wrist["area"] > 600 and self.state_steps > 4: + # the probe pose already points the wrist camera at the sphere; + # keep it instead of returning to the unaimed pose + self.search_center = q.copy() + self._go("wrist") + return + + # phase 0: hold base pose and measure the reference + if self.cal_phase == 0: + if self.cal_wait > 0: + self.cal_wait -= 1 + else: + tip = self.last_tip + if tip is not None and sphere is not None: + self.cal_y0 = np.array([tip[0] - sphere["cx"], + tip[1] - sphere["cy"]]) + self.cal_obs0 = self._obs_q(obs) + # probe shoulder pitch in the likely forward/up direction + q[0] = self.cal_q0[0] - self.cal_delta + self.cal_phase = 1 + self.cal_wait = 7 if self.fast else 10 + elif self.state_steps > 18: + self._go("blind") + elif self.cal_phase == 1: + if self.cal_wait > 0: + self.cal_wait -= 1 + else: + tip = self.last_tip + if tip is not None and sphere is not None: + self.cal_y[0] = np.array([tip[0] - sphere["cx"], + tip[1] - sphere["cy"]]) + self.cal_dq[0] = (self._obs_q(obs)[0] + - self.cal_obs0[0]) + # probe shoulder roll from the base pose + q[:] = self.cal_q0 + q[1] = self.cal_q0[1] - self.cal_delta + self.cal_phase = 2 + self.cal_wait = 7 if self.fast else 10 + elif self.cal_phase == 2: + if self.cal_wait > 0: + self.cal_wait -= 1 + else: + tip = self.last_tip + if tip is not None and sphere is not None: + self.cal_y[1] = np.array([tip[0] - sphere["cx"], + tip[1] - sphere["cy"]]) + self.cal_dq[1] = (self._obs_q(obs)[1] + - self.cal_obs0[1]) + q[:] = self.cal_q0 + self.cal_phase = 3 + self.cal_wait = 3 if self.fast else 4 + else: + if self.cal_wait > 0: + self.cal_wait -= 1 + return + self._build_jacobian() + self.servo_wait = 0 + self.align_count = 0 + self.stall = 0 + self.best_err = 1e9 + self.no_improve = 0 + self._go("servo") + + def _build_jacobian(self): + J = np.zeros((2, 2), dtype=np.float64) + ok = 0 + if self.cal_y0 is not None: + for j in range(2): + if self.cal_y[j] is not None and abs(self.cal_dq[j]) > 0.03: + J[:, j] = (self.cal_y[j] - self.cal_y0) / self.cal_dq[j] + if np.all(np.isfinite(J[:, j])) and np.linalg.norm(J[:, j]) > 1.0: + ok += 1 + else: + J[:, j] = 0.0 + if ok == 0: + self.J = None + else: + self.J = J + + def _solve_step(self, err): + """Return a small joint update that reduces the image error.""" + if self.J is None: + return np.zeros(2) + J = self.J + # only use columns that actually moved the hand + cols = [j for j in range(2) if np.linalg.norm(J[:, j]) > 1.0] + if not cols: + return np.zeros(2) + Js = J[:, cols] + lam = 25.0 + try: + dq = Js.T @ np.linalg.solve(Js @ Js.T + lam * np.eye(2), err) + except np.linalg.LinAlgError: + dq = Js.T @ err / (np.sum(Js * Js) + lam) + dq = np.clip(dq, -0.16, 0.16) + out = np.zeros(2) + for n, j in enumerate(cols): + out[j] = dq[n] + return out + + def _state_servo(self, obs, sphere, wrist): + # The wrist camera is the proximity sensor. A brief glimpse of the + # sphere at the edge of its view is not yet a reason to stop aiming + # with the head: keep the head servo running while the wrist area is + # small, and only switch to the wrist-only mode when the head target + # is lost. + if wrist is not None: + self.wrist_max = max(self.wrist_max, wrist["area"]) + if wrist["area"] > 2200.0: + self.hold_steps = 0 + self._go("hold") + return + if (sphere is None or self.last_tip is None) and wrist is not None \ + and wrist["area"] > 25.0: + self.search_center = self._q().copy() + self._go("wrist") + return + if self.J is None: + self._go("blind") + return + if sphere is None: + if self.frames_missing > 15: + self._go("scan") + return + + # keep the sphere roughly in front; do not fight the arm servo + wz = 0.0 + err_c = sphere["cx"] - CENTER + if abs(err_c) > 12.0: + wz = float(np.clip(-0.022 * err_c, -0.20, 0.20)) + + self.area_ref = self.area_ref or sphere["area"] + q = self._q() + tip = self.last_tip + err = None + if tip is not None: + err = np.array([sphere["cx"] - tip[0], + sphere["cy"] - tip[1]]) + if self.servo_wait <= 0: + dq = self._solve_step(err) + q[0] += dq[0] + q[1] += dq[1] + self._clip_q(self.hand) + self.servo_wait = 3 if self.fast else 5 + else: + self.servo_wait -= 1 + if np.linalg.norm(err) < 3.5: + self.align_count += 1 + else: + self.align_count = 0 + else: + self.align_count = 0 + self.frames_missing += 1 + if self.frames_missing > 10: + self._go("blind") + return + + # approach in small doses. The wrist camera is the proximity sensor; + # the head area ratio is the fallback. + ratio = sphere["area"] / max(self.area_ref, 1.0) + # Absolute size is the reliable proximity cue: the sphere and the + # cameras are the same in every episode, so contact happens at roughly + # the same apparent head-image area. The ratio term handles the + # cases where the sphere starts out closer or farther than usual. + ratio_t = (1.05, 1.12, 1.20, 1.30)[min(self.attempt, 3)] + floor_t = (108.0, 122.0, 140.0, 160.0)[min(self.attempt, 3)] + target_area = min(290.0, max(floor_t, + min(self.area_ref * ratio_t, + self.area_ref + 30.0))) + if self.head_area_at_wrist is not None: + # the head-image area at the moment the wrist first saw the sphere + # gives a data-driven estimate of the contact distance + target_area = min(260.0, max(target_area, + 1.28 * self.head_area_at_wrist)) + if sphere["area"] > 300.0: + self._go("hold") + return + + if sphere["area"] >= target_area and self.wrist_max <= 20.0: + if self.attempt < 3: + self.search_center = q.copy() + self.search_k = 0 + self._go("search") + return + self._go("hold") + return + + # Only walk once the hand has roughly found the sphere, but always + # make slow progress if the arm cannot span the remaining distance. + if self.align_count >= 2: + hi = 0.32 if self.fast else 0.25 + vx = hi if self.wr_area < 300.0 else ( + 0.14 if self.wr_area < 1200.0 else 0.06) + elif ratio > 1.02: + vx = 0.10 + else: + vx = 0.06 + self._set_base(vx=vx, wz=wz) + + # If the arm cannot reduce the error for a while, re-measure the + # Jacobian (the arm configuration has changed) or fall back to a sweep. + if err is not None: + enorm = float(np.linalg.norm(err)) + if enorm < self.best_err - 0.5: + self.best_err = enorm + self.no_improve = 0 + else: + self.no_improve += 1 + if enorm > 6.0: + self.stall += 1 + else: + self.stall = 0 + if self.no_improve > 30: + self.recal += 1 + if self.fast: + self.no_improve = 0 + self.stall = 0 + if (self.recal >= 2 and self.wrist_max < 20.0 + and err is not None and float(np.linalg.norm(err)) > 22.0): + q[:] = self.cal_q0 if self.cal_q0 is not None else q + self._go("blind") + elif self.recal <= 1: + self._start_calib(obs) + else: + q[:] = self.cal_q0 if self.cal_q0 is not None else q + self._go("blind") + + def _state_search(self, obs, sphere, wrist): + """Small local sweep to bring the sphere into the wrist camera.""" + if wrist is not None and wrist["area"] > 18.0: + self.wrist_max = wrist["area"] + self._go("wrist") + return + q = self._q() + center = self.search_center if self.search_center is not None else q.copy() + k = self.search_k + q[0] = center[0] + 0.34 * np.sin(2.0 * np.pi * k / 26.0) + q[1] = center[1] + 0.14 * np.sin(2.0 * np.pi * k / 17.0) + self._clip_q(self.hand) + self.search_k += 1 + if self.state_steps >= (18 if self.fast else 24): + q[0], q[1] = center[0], center[1] + self.attempt = min(self.attempt + 1, 3) + if self.attempt >= 3 and self.wrist_max < 20.0: + self._go("blind") + else: + self._go("servo") + + def _state_wrist(self, obs, sphere, wrist): + if wrist is None: + if self.wrist_max > 600.0 or (sphere is not None + and self.area_ref is not None + and sphere["area"] > 1.45 * self.area_ref): + self._go("hold") + elif self.J is None: + self._go("yaw" if sphere is not None else "scan") + else: + self.attempt = min(self.attempt + 1, 3) + self._go("servo") + return + cx, cy = wrist["cx"], wrist["cy"] + area = wrist["area"] + # lateral base motion is the translation that centres the visual target + vy = float(np.clip(-0.0065 * (cx - CENTER), -0.14, 0.14)) + if abs(vy) < 0.065: + vy = 0.065 if vy > 0 else (-0.065 if vy < 0 else 0.0) + vert = abs(cy - CENTER) + # Vertical centring by pelvis height is a pure translation of the + # camera: raising the body moves the target down in the image and + # lowering the body moves it up, regardless of camera tilt. This is + # also what lets the robot reach low targets by squatting. Do the + # walking while still reasonably upright, then squat in place: the + # controller does not take steps while deeply crouched. + can_crouch = self.height > 0.421 + can_stand = self.height < 0.799 + if area < 260.0: + # far away: walk first; stand back up if a previous squat ended + vx = 0.09 + if self.height < 0.62: + vx = 0.0 + self.height = float(np.clip(self.height + 0.006, 0.42, 0.74)) + elif (cy > CENTER + 7.0 and can_crouch) or \ + (cy < CENTER - 7.0 and can_stand): + vx = 0.0 + self.height = float(np.clip( + self.height + 0.0025 * (CENTER - cy), 0.42, 0.80)) + else: + vx = 0.09 if area < 1200.0 else (0.06 if area < 2200.0 else 0.0) + wz = 0.0 + if abs(cx - CENTER) > 12.0: + wz = float(np.clip(-0.020 * (cx - CENTER), -0.22, 0.22)) + self._set_base(vx=vx, vy=vy, wz=wz) + close = area > 2200.0 and (vert < 30.0 or + (self.height <= 0.421 and cy > CENTER) or + (self.height >= 0.799 and cy < CENTER)) + if close or (self.wrist_max > 700.0 and area < 0.35 * self.wrist_max): + self.hold_steps = 0 + self._go("hold") + elif self.state_steps > 90 and area < 80.0: + # the glimpse was transient; resume the head-based approach + self.attempt = min(self.attempt + 1, 3) + if self.J is None: + self._go("yaw" if sphere is not None else "scan") + else: + self._go("servo") + + def _state_blind(self, obs, sphere, wrist): + """Fallback: sweep the arm through a wide range while walking.""" + if wrist is not None and wrist["area"] > 18.0: + self.wrist_max = wrist["area"] + self.search_center = self._q().copy() + self._go("wrist") + return + q = self._q() + if self.cal_q0 is not None: + base = self.cal_q0 + else: + base = q.copy() + self.cal_q0 = base.copy() + k = self.state_steps + # sweep smoothly through both possible "lift" directions, then back + if k < 70: + u = k / 70.0 + s = 0.5 - 0.5 * np.cos(np.pi * u) + q[0] = base[0] - 1.65 * s + elif k < 140: + u = min(k - 70, 70) / 70.0 + s = 0.5 - 0.5 * np.cos(np.pi * u) + q[0] = base[0] - 1.65 + (1.65 + 0.90) * s + elif k < 210: + u = min(k - 140, 70) / 70.0 + s = 0.5 - 0.5 * np.cos(np.pi * u) + q[0] = base[0] + 0.90 - (0.90 + 1.65) * s + else: + q[0] = base[0] - 1.65 + q[1] = base[1] + 0.25 * np.sin(2.0 * np.pi * k / 55.0) + self._clip_q(self.hand) + if sphere is not None: + err = sphere["cx"] - CENTER + if abs(err) > 6.0: + self._set_base(wz=float(np.clip(-0.022 * err, -0.22, 0.22))) + ratio = sphere["area"] / max(self.area_ref or sphere["area"], 1.0) + if ratio < 1.45: + self._set_base(vx=0.12, + wz=float(np.clip(-0.022 * err, -0.22, 0.22)) + if abs(err) > 6.0 else 0.0) + if sphere is None and self.frames_missing > 25: + self._go("scan") + if self.state_steps > 210: + self._go("hold") + + def _state_hold(self, obs, sphere, wrist): + self._set_base() + self.hold_steps += 1 + # Keep a gentle forward pressure on the target. The last few + # centimetres are easy to miss because the wrist camera stops seeing + # the sphere when the hand is right on it, so creep instead of + # stopping dead. + if sphere is not None and sphere["area"] > 330.0: + vx = 0.0 + else: + vx = 0.060 + self._set_base(vx=vx) + # if the hold did not end the episode, try again with the other arm + if self.fell: + return + if self.hold_steps > 85: + remaining = self.limit - self.t + # If the wrist camera or the head image still shows the target + # close by, keep pressing: switching arms at that moment would + # break a contact that is only a few steps short of the 1 s latch. + near = self.wr_area > 150.0 or ( + sphere is not None and sphere["area"] > 130.0) + if near: + self.hold_steps = 85 + elif remaining > 110: + self.hand = "R" if self.hand == "L" else "L" + self.attempt = 0 + self.wrist_max = 0.0 + self.head_area_at_wrist = None + self.J = None + self.cal_q0 = None + self.recal = 0 + self.hold_steps = 0 + self.area_ref = None + self.frames_missing = 0 + self.last_tip = None + self.applied_q[self._arm_index()] = self._q().copy() + self._go("init") + else: + self.hold_steps = 85 diff --git a/policies/reach_target_multi_modal/gpt61sol-s1/episodes.csv b/policies/reach_target_multi_modal/gpt61sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..331e3d0d49ca2b651f164b75dd929fb19491442a --- /dev/null +++ b/policies/reach_target_multi_modal/gpt61sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,271,success,0 +620001,1,145,success,0 +620002,1,144,success,0 +620003,1,100,success,0 +620004,1,416,success,0 +620005,1,98,success,0 +620006,1,456,success,0 +620007,1,143,success,0 +620008,1,143,success,0 +620009,1,143,success,0 +620010,1,251,success,0 +620011,1,108,success,0 +620012,1,375,success,0 +620013,1,105,success,0 +620014,1,342,success,0 +620015,1,107,success,0 +620016,1,139,success,0 +620017,1,359,success,0 +620018,1,137,success,0 +620019,1,427,success,0 +620020,1,278,success,0 +620021,1,107,success,0 +620022,1,133,success,0 +620023,0,700,timeout,0 +620024,1,142,success,0 +620025,1,107,success,0 +620026,0,700,timeout,0 +620027,0,700,timeout,0 +620028,1,471,success,0 +620029,1,395,success,0 +620030,1,369,success,0 +620031,0,700,timeout,0 +620032,1,450,success,0 +620033,1,135,success,0 +620034,1,99,success,0 +620035,1,148,success,0 +620036,1,467,success,0 +620037,1,137,success,0 +620038,1,173,success,0 +620039,1,155,success,0 +620040,1,148,success,0 +620041,1,164,success,0 +620042,1,344,success,0 +620043,0,700,timeout,0 +620044,1,135,success,0 +620045,1,535,success,0 +620046,1,115,success,0 +620047,1,382,success,0 +620048,1,109,success,0 +620049,1,145,success,0 +620050,1,144,success,0 +620051,0,700,timeout,0 +620052,0,700,timeout,0 +620053,1,449,success,0 +620054,0,700,timeout,0 +620055,1,413,success,0 +620056,1,151,success,0 +620057,1,136,success,0 +620058,1,279,success,0 +620059,1,361,success,0 +620060,1,99,success,0 +620061,1,358,success,0 +620062,1,237,success,0 +620063,1,395,success,0 +620064,1,431,success,0 +620065,0,700,timeout,0 +620066,0,700,timeout,0 +620067,1,415,success,0 +620068,1,99,success,0 +620069,1,138,success,0 +620070,1,391,success,0 +620071,1,136,success,0 +620072,1,220,success,0 +620073,1,279,success,0 +620074,1,145,success,0 +620075,0,700,timeout,0 +620076,0,700,timeout,0 +620077,1,137,success,0 +620078,1,147,success,0 +620079,1,111,success,0 +620080,1,147,success,0 +620081,0,700,timeout,0 +620082,1,136,success,0 +620083,1,251,success,0 +620084,1,116,success,0 +620085,0,700,timeout,0 +620086,0,700,timeout,0 +620087,0,700,timeout,0 +620088,0,700,timeout,0 +620089,0,700,timeout,0 +620090,1,399,success,0 +620091,1,106,success,0 +620092,1,138,success,0 +620093,1,370,success,0 +620094,1,345,success,0 +620095,1,477,success,0 +620096,1,108,success,0 +620097,1,176,success,0 +620098,0,700,timeout,0 +620099,1,136,success,0 diff --git a/policies/reach_target_multi_modal/gpt61sol-s1/policy.py b/policies/reach_target_multi_modal/gpt61sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a7e18f93a246bc08e4ecaf8aaa3780b79b3bf890 --- /dev/null +++ b/policies/reach_target_multi_modal/gpt61sol-s1/policy.py @@ -0,0 +1,153 @@ +"""Deterministic visual positioning and arm search; no learned parameters.""" +import numpy as np +import cv2 + +class Policy: + + def see(self, tools): + im = tools.image('head') + r, g, b = [im[:, :, i].astype(float) for i in range(3)] + mask = ((r > 65) & (r > 1.6 * g + 15) & (r > 1.6 * b + 15)).astype(np.uint8) + # The target brightens while the touch condition holds. + self.contact = bool(np.any((r > 235) & (g < 65) & (b < 65))) + n, labels, stats, cent = cv2.connectedComponentsWithStats(mask) + self.tip = None + white = (im.min(2) > 100) & (im.max(2).astype(float) - im.min(2) < 60) + if hasattr(self, 'right'): + if self.right: + white[:, :42] = False + else: + white[:, 42:] = False + ys, xs = np.where(white) + if len(xs) > 6: + k = np.argsort(ys)[:6] + self.tip = np.array([np.mean(xs[k]), np.mean(ys[k])]) + if n < 2: + return None + k = 1 + np.argmax(stats[1:, 4]) + ys, xs = np.where(labels == k) + (u, v), rad = cv2.minEnclosingCircle(np.column_stack((xs, ys)).astype(np.float32)) + bright = self.contact + # A red crescent behind the hand is an unreliable new target center. + if getattr(self, 'mode', None) == 'reach' and self.obsim is not None: + if rad < 0.8 * self.obsim[2] or stats[k, 4] < 0.4 * np.pi * self.obsim[2] ** 2: + return None + return np.array([u, v, rad, float(bright)]) + + def reset(self, obs, tools): + self.mode = 'walk' + self.obsim = None + self.a = np.asarray(tools.hold_action(), dtype=float) + self.obsim = self.see(tools) + self.right = self.obsim is None or self.obsim[0] >= 42 + self.mode = 'walk' + self.round = 0 + self.since = 0 + self.goal = None + self.arm = np.array([-0.3, 0, 0.2 if self.right else -0.2, 0.3, 0, 0, 0.0]) + self.scan = 0 + self.height = 0.74 + self.active = 0 + self.lastq = obs['low_dim_obs'][18:22].copy() + + def setgoal(self, obs): + q = obs['low_dim_obs'] + yaw = q[21] + c, s = (np.cos(yaw), np.sin(yaw)) + u, v, r, _ = self.obsim + self.pixgoal = np.array([59 if self.right else 24, 32]) + shift = (self.pixgoal - np.array([u, v])) * 0.055 / max(r, 6) + shift = np.clip(shift, -0.27, 0.27) + dx, dy = (shift[1], shift[0]) + self.goal = q[18:20] + [c * dx - s * dy, s * dx + c * dy] + + def act(self, obs, tools): + t = obs['t'] + q = obs['low_dim_obs'] + a = self.a.copy() + a[:4] = [0, 0, self.height, 0] + # Maintain the target projection during hand occlusion and squatting. + if self.mode == 'reach' and self.obsim is not None: + pose = q[18:22] + delta = pose - self.lastq + c, s = (np.cos(pose[3]), np.sin(pose[3])) + dx = c * delta[0] + s * delta[1] + dy = -s * delta[0] + c * delta[1] + oldr = max(self.obsim[2], 3) + depth = max(0.12, 3 / oldr + delta[2]) + newr = 3 / depth + scale = newr / oldr + self.obsim[:2] = 42 + (self.obsim[:2] - 42) * scale + np.array([dy, dx]) * newr / 0.055 + self.obsim[2] = newr + self.lastq = q[18:22].copy() + if t % 4 == 0: + v = self.see(tools) + if v is not None: + self.obsim = v + if self.contact and self.mode != 'reach': + self.mode = 'reach' + self.since = t + if self.goal is None: + if self.obsim is None: + a[0] = 0.12 + return a + self.setgoal(obs) + if self.mode == 'walk': + # Close the movement loop on pelvis position and velocity. + d = self.goal - q[18:20] + c, s = (np.cos(q[21]), np.sin(q[21])) + db = np.array([c * d[0] + s * d[1], -s * d[0] + c * d[1]]) + vel = q[40:42] + vb = np.array([c * vel[0] + s * vel[1], -s * vel[0] + c * vel[1]]) + cmd = np.clip(1.7 * db - 0.35 * vb, -0.22, 0.22) + if np.linalg.norm(d) < 0.016 and t - self.since > 25 or t - self.since > 175: + self.mode = 'settle' + self.since = t + else: + if np.linalg.norm(cmd) < 0.06 and np.linalg.norm(d) > 0.016: + cmd *= 0.06 / max(np.linalg.norm(cmd), 1e-06) + a[:2] = cmd + elif self.mode == 'settle': + if t - self.since > 35: + self.round += 1 + if np.linalg.norm(self.pixgoal - self.obsim[:2]) > 5 and self.round < 2 and (t < 250): + self.setgoal(obs) + self.mode = 'walk' + self.since = t + else: + self.mode = 'reach' + self.since = t + elif self.mode == 'reach' and t % 4 == 0: + if self.contact: + self.active += 4 + else: + self.active = 0 + self.scan += 4 + if self.tip is not None and self.obsim is not None: + u, v, r, _ = self.obsim + desired = np.array([u - 5 if self.right else u + 5, v - 3]) + delta = desired - self.tip + self.arm[0] += np.clip(0.007 * delta[1], -0.035, 0.035) + self.arm[1] -= np.clip(0.006 * delta[0], -0.025, 0.025) + self.arm[1] = np.clip(self.arm[1], -0.7 if self.right else -0.12, 0.12 if self.right else 0.7) + if self.scan < 60: + self.arm[3] = 0.3 + elif self.scan < 90: + self.arm[3] = 0.3 * (90 - self.scan) / 30 + elif self.scan < 300: + # Explore low targets before raising and bending the arm. + self.arm[3] = 0 + self.height = max(0.43, 0.74 - (self.scan - 90) * 0.0015) + elif self.scan < 370: + self.height = min(0.78, self.height + 0.02) + self.arm[3] = 1.3 + elif self.scan < 470: + self.height = 0.78 + self.arm[3] = 1.3 + 0.75 * (self.scan - 370) / 100 + else: + self.height = 0.74 + self.arm[3] = 1.0 + self.arm[0] = np.clip(self.arm[0], -2.3, 0.5) + start = 11 if self.right else 4 + a[start:start + 7] = self.arm + return a diff --git a/policies/reach_target_multi_modal/gpt61sol-s2/episodes.csv b/policies/reach_target_multi_modal/gpt61sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..7498a7f460f1942812d427cd39ece320f3583bfd --- /dev/null +++ b/policies/reach_target_multi_modal/gpt61sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,257,success,0 +620001,1,275,success,0 +620002,1,525,success,0 +620003,1,527,success,0 +620004,1,523,success,0 +620005,1,317,success,0 +620006,1,256,success,0 +620007,1,253,success,0 +620008,1,516,success,0 +620009,1,442,success,0 +620010,1,233,success,0 +620011,1,390,success,0 +620012,1,447,success,0 +620013,1,377,success,0 +620014,1,597,success,0 +620015,1,343,success,0 +620016,1,523,success,0 +620017,1,540,success,0 +620018,1,334,success,0 +620019,1,559,success,0 +620020,1,477,success,0 +620021,1,309,success,0 +620022,1,543,success,0 +620023,1,527,success,0 +620024,1,250,success,0 +620025,1,344,success,0 +620026,1,453,success,0 +620027,1,546,success,0 +620028,1,582,success,0 +620029,1,545,success,0 +620030,1,597,success,0 +620031,1,415,success,0 +620032,1,445,success,0 +620033,1,282,success,0 +620034,1,515,success,0 +620035,1,253,success,0 +620036,0,700,timeout,0 +620037,1,366,success,0 +620038,1,254,success,0 +620039,1,397,success,0 +620040,1,399,success,0 +620041,1,481,success,0 +620042,1,490,success,0 +620043,1,433,success,0 +620044,1,314,success,0 +620045,1,515,success,0 +620046,1,337,success,0 +620047,1,637,success,0 +620048,1,345,success,0 +620049,1,450,success,0 +620050,1,259,success,0 +620051,1,436,success,0 +620052,1,594,success,0 +620053,0,700,timeout,0 +620054,1,386,success,0 +620055,1,481,success,0 +620056,1,497,success,0 +620057,1,372,success,0 +620058,1,567,success,0 +620059,1,341,success,0 +620060,1,246,success,0 +620061,1,504,success,0 +620062,1,524,success,0 +620063,1,373,success,0 +620064,1,493,success,0 +620065,1,253,success,0 +620066,1,473,success,0 +620067,0,700,timeout,0 +620068,1,331,success,0 +620069,1,372,success,0 +620070,1,353,success,0 +620071,1,446,success,0 +620072,1,492,success,0 +620073,1,416,success,0 +620074,1,496,success,0 +620075,1,516,success,0 +620076,1,432,success,0 +620077,1,453,success,0 +620078,1,465,success,0 +620079,1,276,success,0 +620080,1,381,success,0 +620081,1,442,success,0 +620082,1,415,success,0 +620083,1,470,success,0 +620084,1,423,success,0 +620085,1,514,success,0 +620086,1,415,success,0 +620087,1,443,success,0 +620088,1,343,success,0 +620089,1,445,success,0 +620090,1,365,success,0 +620091,1,355,success,0 +620092,1,607,success,0 +620093,1,451,success,0 +620094,1,541,success,0 +620095,1,239,success,0 +620096,1,255,success,0 +620097,1,301,success,0 +620098,1,473,success,0 +620099,1,362,success,0 diff --git a/policies/reach_target_multi_modal/gpt61sol-s2/policy.py b/policies/reach_target_multi_modal/gpt61sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..0df8622e229458e412f2326918bf622080d18544 --- /dev/null +++ b/policies/reach_target_multi_modal/gpt61sol-s2/policy.py @@ -0,0 +1,152 @@ +"""Deterministic colour vision and position feedback for touching the sphere.""" +import cv2 +import numpy as np +import itertools + +def wrist_sphere(im): + """Recover the sphere's circular outline, including partially cropped views.""" + rgb = im.astype(float) + mask = ((rgb[:, :, 0] > 50) + & (rgb[:, :, 0] > rgb[:, :, 1] * 1.7 + 10) + & (rgb[:, :, 0] > rgb[:, :, 2] * 1.5 + 10)).astype(np.uint8) + contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) + if not contours: + return None + points = max(contours, key=cv2.contourArea)[:, 0, :].astype(float) + points = points[(points[:, 0] > 1) & (points[:, 0] < 82) + & (points[:, 1] > 1) & (points[:, 1] < 82)] + if len(points) < 12: + return None + sample = points[np.linspace(0, len(points) - 1, + min(22, len(points))).astype(int)] + best, best_support = None, 0 + # Each candidate is the exact circumcircle of three contour points. + for indices in itertools.combinations(range(len(sample)), 3): + p1, p2, p3 = sample[list(indices)] + u, v = p2 - p1, p3 - p1 + determinant = u[0] * v[1] - u[1] * v[0] + if abs(determinant) < 5: + continue + lengths = np.array([u @ u, v @ v]) * .5 + center = p1 + np.array([ + (lengths[0] * v[1] - lengths[1] * u[1]) / determinant, + (u[0] * lengths[1] - v[0] * lengths[0]) / determinant]) + radius = np.linalg.norm(center - p1) + if radius < 4 or radius > 350: + continue + support = np.count_nonzero( + abs(np.linalg.norm(points - center, axis=1) - radius) < .9) + if support > best_support: + best_support, best = support, np.r_[center, radius] + return best + + +class Policy: + @staticmethod + def sphere(im): + a=im.astype(np.int16) + m=((a[:,:,0]>65)&(a[:,:,0]>1.7*a[:,:,1]+10)&(a[:,:,0]>1.5*a[:,:,2]+10)).astype(np.uint8) + n,labels,stats,cent=cv2.connectedComponentsWithStats(m) + if n<2:return None + k=1+np.argmax(stats[1:,cv2.CC_STAT_AREA]) + if stats[k,cv2.CC_STAT_AREA]<5:return None + x,y,w,h,area=stats[k] + if x<=0 or y<=0 or x+w>=84 or y+h>=84: + fit=wrist_sphere(im) + if fit is not None:return np.r_[fit[:2],fit[2]*.95] + return np.r_[cent[k],np.sqrt(area/np.pi)] + + @staticmethod + def camera_position(s): + # Approximate pinhole coordinates, scaled by the sphere radius. + u,v,r=s + return .043*np.array([(u-41.5)/r,(v-41.5)/r,70/r]) + + def reset(self,obs,tools): + self.hold=np.asarray(tools.hold_action(),dtype=np.float32) + self.phase='align' + self.goal=self.camera_position(np.array([42.66,17.34,6.31])) + self.height=.74 + self.error=np.zeros(3) + self.height_error=0. + self.stable=0 + self.destination=None + self.seen=False + self.initial_x=float(obs["low_dim_obs"][18]) + self.freeze_until=0 + self.start=0 + self.reach_height=.70 + # Fixed proportional feedback: shoulder pitch, shoulder yaw, height. + self.gain=np.linalg.inv(np.array([[-3.,2.,8.],[-7.,.6,9.],[-7.,-.7,14.]])) + self.q=np.array([-1.2,-.1,-.4,1.2,0,.3,0]) + + def act(self,obs,tools): + a=self.hold.copy();p=obs['low_dim_obs'];t=obs['t'] + a[3]=np.clip(-p[21]*3,-.25,.25) + a[2]=self.height + if self.phase=='align': + if t%5==0: + s=self.sphere(tools.image('head')) + if s is not None: + self.seen=True + dc=self.camera_position(s)-self.goal + sn=np.sin(1.12);cs=np.cos(1.12) + self.error=np.array([cs*dc[2]-sn*dc[1],-dc[0],-sn*dc[2]-cs*dc[1]]) + yaw=p[21] + c=np.cos(yaw);si=np.sin(yaw) + world=np.array([c*self.error[0]-si*self.error[1],si*self.error[0]+c*self.error[1]]) + dest=p[18:20]+world + self.destination=dest if self.destination is None else .88*self.destination+.12*dest + if self.destination is not None: + dd=self.destination-p[18:20] + c=np.cos(p[21]);si=np.sin(p[21]) + dx=c*dd[0]+si*dd[1];dy=-si*dd[0]+c*dd[1] + else:dx,dy=self.error[:2] + dz=self.error[2] + for i,d in enumerate([dx,dy]): + if abs(d)>.011:a[i]=np.sign(d)*np.clip(abs(d)*2.3,.075,.25) + if not self.seen: + a[0]=.20 if p[18]25 and abs(dx)<.015 and abs(dy)<.015: + self.stable+=1 + else:self.stable=0 + if self.seen and (self.stable>=20 or t>=260): + self.height=float(np.clip(.74+dz,.47,.79)) + self.phase='height';self.start=t + elif self.phase=='height': + if t%5==0: + s=self.sphere(tools.image('head')) + if s is not None: + dc=self.camera_position(s)-self.goal + dz=-np.sin(1.12)*dc[2]-np.cos(1.12)*dc[1] + self.height_error=float(dz) + self.height=float(np.clip(.6*self.height+.4*(p[20]+dz-.007),.45,.79)) + if t-self.start>=90: + self.reach_height=max(.4,self.height-.04) + self.reach_z=float(p[20]-.045) + self.q[0]-=float(np.clip(self.height_error/.26,-.25,.45)) + self.phase='reach';self.start=t + else: + duration=t-self.start + frac=min(1.,duration/35.) + a[4:11]=self.q*frac + a[18]=0 + if duration>=40: + if duration>=105 and t%10==0 and t>=self.freeze_until: + s=wrist_sphere(tools.image('left_wrist')) + if s is not None: + feat=np.r_[(s[:2]-42)/s[2],60/s[2]] + err=np.array([-.32,-.47,.98])-feat + if np.linalg.norm(err)<.14 and abs(p[42])<.025: + self.freeze_until=t+80 + elif np.linalg.norm(err)>.10: + move=self.gain@err + move*=min(1.,.07/max(.001,abs(move[0]),abs(move[1])),.012/max(.001,abs(move[2]))) + self.q[0]=np.clip(self.q[0]+move[0]*.3,-1.9,-.7) + self.q[2]=np.clip(self.q[2]+move[1]*.3,-1.1,.2) + self.reach_z=float(np.clip(self.reach_z+move[2]*.3,.43,.77)) + if t>=self.freeze_until:self.reach_height=float(np.clip(self.reach_height+.012*(self.reach_z-p[20]),.4,.79)) + a[2]=self.reach_height + else:a[2]=self.height + # Pause corrections near contact so the one-second dwell can complete. + return a diff --git a/policies/reach_target_multi_modal/gpt61sol-s3/episodes.csv b/policies/reach_target_multi_modal/gpt61sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..a5fae8c7bbc7a620e3deb7fecf82df6f1176b468 --- /dev/null +++ b/policies/reach_target_multi_modal/gpt61sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,238,success,0 +620001,1,243,success,0 +620002,1,217,success,0 +620003,1,342,success,0 +620004,1,404,success,0 +620005,1,212,success,0 +620006,1,250,success,0 +620007,1,223,success,0 +620008,1,375,success,0 +620009,1,223,success,0 +620010,1,270,success,0 +620011,1,220,success,0 +620012,1,252,success,0 +620013,1,205,success,0 +620014,1,239,success,0 +620015,1,269,success,0 +620016,1,380,success,0 +620017,1,318,success,0 +620018,1,277,success,0 +620019,1,244,success,0 +620020,1,247,success,0 +620021,1,482,success,0 +620022,1,399,success,0 +620023,1,253,success,0 +620024,1,237,success,0 +620025,1,197,success,0 +620026,1,207,success,0 +620027,1,232,success,0 +620028,1,245,success,0 +620029,1,239,success,0 +620030,1,241,success,0 +620031,1,254,success,0 +620032,1,232,success,0 +620033,1,232,success,0 +620034,1,220,success,0 +620035,1,233,success,0 +620036,1,251,success,0 +620037,1,283,success,0 +620038,1,233,success,0 +620039,1,229,success,0 +620040,1,228,success,0 +620041,1,243,success,0 +620042,1,247,success,0 +620043,1,216,success,0 +620044,1,231,success,0 +620045,1,208,success,0 +620046,1,391,success,0 +620047,1,242,success,0 +620048,1,265,success,0 +620049,1,241,success,0 +620050,1,532,success,0 +620051,1,265,success,0 +620052,1,474,success,0 +620053,1,240,success,0 +620054,1,322,success,0 +620055,1,311,success,0 +620056,1,208,success,0 +620057,1,569,success,0 +620058,1,239,success,0 +620059,1,312,success,0 +620060,1,468,success,0 +620061,1,294,success,0 +620062,1,234,success,0 +620063,1,231,success,0 +620064,1,252,success,0 +620065,1,384,success,0 +620066,1,552,success,0 +620067,1,456,success,0 +620068,1,491,success,0 +620069,1,218,success,0 +620070,1,241,success,0 +620071,1,234,success,0 +620072,1,233,success,0 +620073,1,248,success,0 +620074,1,308,success,0 +620075,1,210,success,0 +620076,1,232,success,0 +620077,1,229,success,0 +620078,1,235,success,0 +620079,1,514,success,0 +620080,1,243,success,0 +620081,1,225,success,0 +620082,1,237,success,0 +620083,1,310,success,0 +620084,1,474,success,0 +620085,1,172,success,0 +620086,1,328,success,0 +620087,1,220,success,0 +620088,1,504,success,0 +620089,1,258,success,0 +620090,1,269,success,0 +620091,1,274,success,0 +620092,1,233,success,0 +620093,1,316,success,0 +620094,1,237,success,0 +620095,1,234,success,0 +620096,1,386,success,0 +620097,1,236,success,0 +620098,1,206,success,0 +620099,1,224,success,0 diff --git a/policies/reach_target_multi_modal/gpt61sol-s3/policy.py b/policies/reach_target_multi_modal/gpt61sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..3bc4e482795c0f932150093e4da12933d6f92a74 --- /dev/null +++ b/policies/reach_target_multi_modal/gpt61sol-s3/policy.py @@ -0,0 +1,152 @@ +"""Hand-written deterministic visual servoing for touching the red sphere. + +The head view selects a hand and initializes the reach. The wrist view closes +an angular feedback loop; coordinated shoulder/elbow motion advances the hand. +All scene information comes from the three permitted robot cameras. +""" + +import cv2 +import numpy as np + + +def sphere(image): + """Locate the largest red region, including the sphere's shaded surface.""" + rgb = image.astype(np.float32) + mask = ( + (rgb[:, :, 0] > 18) + & (rgb[:, :, 0] > 1.6 * rgb[:, :, 1]) + & (rgb[:, :, 0] > 1.5 * rgb[:, :, 2]) + ).astype(np.uint8) + count, labels, stats, _ = cv2.connectedComponentsWithStats(mask) + if count <= 1: + return None + component = 1 + np.argmax(stats[1:, 4]) + if stats[component, 4] < 4: + return None + ys, xs = np.where(labels == component) + (x, y), radius = cv2.minEnclosingCircle( + np.stack((xs, ys), axis=1).astype(np.float32) + ) + return np.array([x, y, radius, stats[component, 4]], dtype=float) + + +class Policy: + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=float) + h = sphere(tools.image("head")) + self.side = "right" if h is not None and h[0] > 42 else "left" + self.idx = 11 if self.side == "right" else 4 + self.a[self.idx:self.idx + 7] = 0 + if h is not None: + self.a[self.idx] = np.clip(.018 * (h[1] - 20), -.6, .35) + self.a[self.idx + 2] = .006 * ( + (69 if self.side == "right" else 14) - h[0] + ) + self.a[18:20] = .6 + self.seen = False + self.lost = 0 + self.target = None + self.freeze = False + self.freeze_t = 0 + self.bright = False + self.dark = 0 + self.base0 = obs["low_dim_obs"][18:22].copy() + self.walk_end = None + self.aimed = False + self.recover_to = None + self.retries = 0 + # Apparent size limits the initial approach for nearer placements. + self.advance = .13 if h is None else float( + np.clip(.13 - .11 * (h[2] - 7.9), .02, .13) + ) + + def act(self, obs, tools): + t = obs["t"] + ld = obs["low_dim_obs"] + + # If the target passes behind the wrist, retract and reacquire it. + if self.recover_to is not None: + self.a[:4] = [-.12, 0, .74, 0] + self.a[4:18] = 0 + if ld[18] < self.recover_to: + self.recover_to = None + self.walk_end = t + self.aimed = False + self.seen = False + self.lost = 0 + self.target = None + self.a[0] = 0 + return self.a.copy() + + # Close the walking loop with pelvis position and heading feedback. + if self.walk_end is None: + self.a[:4] = [ + .15, 0, .74, + np.clip(2 * (self.base0[3] - ld[21]), -.3, .3), + ] + self.a[4:18] = 0 + if ld[18] - self.base0[0] > self.advance or t > 150: + self.walk_end = t + self.a[0] = 0 + return self.a.copy() + if t - self.walk_end < 55: + self.a[:4] = [0, 0, .74, 0] + return self.a.copy() + + if not self.aimed: + h = sphere(tools.image("head")) + if h is not None: + self.a[self.idx] = np.clip(.018 * (h[1] - 20), -.6, .35) + self.a[self.idx + 2] = .006 * ( + (69 if self.side == "right" else 14) - h[0] + ) + self.aimed = True + + # The sphere brightens on contact. Hold the pose while it stays bright. + if t % 2 == 0: + image = tools.image(self.side + "_wrist").astype(float) + red = ( + (image[:, :, 0] > 1.6 * image[:, :, 1]) + & (image[:, :, 0] > 1.5 * image[:, :, 2]) + ) + self.bright = np.sum(red & (image[:, :, 0] > 225)) > 60 + self.dark = 0 if self.bright else self.dark + 2 + if self.bright and not self.freeze: + self.freeze = True + self.freeze_t = t + if self.freeze and self.dark > 12: + self.freeze = False + if self.freeze: + self.a[:4] = [0, 0, .74, 0] + return self.a.copy() + + self.a[:4] = [0, 0, .74, 0] + if t % 4 == 0: + self.target = sphere(tools.image(self.side + "_wrist")) + if self.target is not None: + self.lost = 0 + self.seen = True + x, y, _, _ = self.target + self.a[self.idx] += np.clip((y - 28) * .00085, -.04, .04) + self.a[self.idx + 2] += np.clip(-(x - 42) * .00075, -.04, .04) + else: + self.lost += 4 + if ((self.seen and self.lost > 24) or + (not self.seen and self.lost > 80)) and self.retries < 3: + self.recover_to = float(ld[18] - .055) + self.retries += 1 + if not self.seen: + self.a[self.idx] -= .012 + self.a[self.idx] = np.clip(self.a[self.idx], -1.8, .8) + self.a[self.idx + 2] = np.clip(self.a[self.idx + 2], -.9, .9) + + if self.target is not None and t > 35: + x, y, _, _ = self.target + if abs(x - 42) < 16 and abs(y - 28) < 18: + if self.a[self.idx + 3] < 1.2: + delta = min(.004, 1.4 - self.a[self.idx + 3]) + self.a[self.idx + 3] += delta + self.a[self.idx] -= delta + else: + self.a[0] = .08 + return self.a.copy() diff --git a/policies/reach_target_multi_modal/gpt61terra-s1/episodes.csv b/policies/reach_target_multi_modal/gpt61terra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..e683c3fec90cbd3b11d44322936687e08ed9141e --- /dev/null +++ b/policies/reach_target_multi_modal/gpt61terra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,397,success,0 +620001,1,289,success,0 +620002,1,137,success,0 +620003,0,700,timeout,0 +620004,1,126,success,0 +620005,1,133,success,0 +620006,1,374,success,0 +620007,1,373,success,0 +620008,1,223,success,0 +620009,1,140,success,0 +620010,1,136,success,0 +620011,1,140,success,0 +620012,1,134,success,0 +620013,1,409,success,0 +620014,1,396,success,0 +620015,0,700,timeout,0 +620016,1,223,success,0 +620017,1,127,success,0 +620018,1,143,success,0 +620019,1,373,success,0 +620020,1,136,success,0 +620021,1,203,success,0 +620022,1,196,success,0 +620023,0,700,timeout,0 +620024,1,461,success,0 +620025,1,250,success,0 +620026,1,371,success,0 +620027,1,289,success,0 +620028,0,700,timeout,0 +620029,1,126,success,0 +620030,1,397,success,0 +620031,0,700,timeout,0 +620032,1,290,success,0 +620033,0,700,timeout,0 +620034,1,136,success,0 +620035,1,372,success,0 +620036,1,217,success,0 +620037,1,366,success,0 +620038,0,700,timeout,0 +620039,1,141,success,0 +620040,1,138,success,0 +620041,1,140,success,0 +620042,1,127,success,0 +620043,1,375,success,0 +620044,1,397,success,0 +620045,0,700,timeout,0 +620046,0,700,timeout,0 +620047,1,126,success,0 +620048,0,700,timeout,0 +620049,1,139,success,0 +620050,1,398,success,0 +620051,1,392,success,0 +620052,1,454,success,0 +620053,1,216,success,0 +620054,1,379,success,0 +620055,1,632,success,0 +620056,1,136,success,0 +620057,1,127,success,0 +620058,1,373,success,0 +620059,1,632,success,0 +620060,1,128,success,0 +620061,1,640,success,0 +620062,1,133,success,0 +620063,1,368,success,0 +620064,1,140,success,0 +620065,0,700,timeout,0 +620066,1,137,success,0 +620067,1,645,success,0 +620068,1,128,success,0 +620069,0,700,timeout,0 +620070,1,290,success,0 +620071,1,143,success,0 +620072,1,137,success,0 +620073,1,136,success,0 +620074,1,289,success,0 +620075,1,137,success,0 +620076,1,460,success,0 +620077,1,288,success,0 +620078,1,461,success,0 +620079,1,202,success,0 +620080,1,141,success,0 +620081,1,368,success,0 +620082,1,135,success,0 +620083,1,137,success,0 +620084,1,245,success,0 +620085,1,131,success,0 +620086,1,395,success,0 +620087,0,700,timeout,0 +620088,1,373,success,0 +620089,1,396,success,0 +620090,0,700,timeout,0 +620091,1,231,success,0 +620092,1,139,success,0 +620093,1,640,success,0 +620094,1,127,success,0 +620095,1,126,success,0 +620096,1,222,success,0 +620097,1,137,success,0 +620098,1,143,success,0 +620099,1,373,success,0 diff --git a/policies/reach_target_multi_modal/gpt61terra-s1/policy.py b/policies/reach_target_multi_modal/gpt61terra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..120865293f86d0acbc18cd1883a09fc0fafb9125 --- /dev/null +++ b/policies/reach_target_multi_modal/gpt61terra-s1/policy.py @@ -0,0 +1,66 @@ +import numpy as np +import cv2 + +def ball(im): + im=im.astype(np.float32) + mask=((im[:,:,0]>70)&(im[:,:,0]>im[:,:,1]*1.6)&(im[:,:,0]>im[:,:,2]*1.4)).astype(np.uint8) + n,lab,s,c=cv2.connectedComponentsWithStats(mask) + if n<2:return None + k=1+np.argmax(s[1:,4]); x,y,w,h,area=s[k] + if area<5:return None + return float(x+(w-1)/2),float(y+(h-1)/2),float(w),float(h) + +class Policy: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action(),dtype=np.float32) + self.x0=float(obs['low_dim_obs'][18]);self.phase=0;self.wait=0;self.target=None;self.start=0;self.moved=False;self.shifted=False + def act(self,obs,tools): + t=obs['t'];a=self.a.copy() + if self.phase==0: + a[0]=.25 + if obs['low_dim_obs'][18]>=self.x0+.09 or t>90: + a[0]=0;self.phase=1 + return a + if self.phase==1: + self.wait+=1 + if self.wait==35: + self.target=ball(tools.image('head')) + x,y,w,h=self.target if self.target else (50,32,15,15) + if not self.moved and (x<38 or x>64): + self.ygoal=float(obs['low_dim_obs'][19])+float(np.clip((51-x)*.005, -.16, .16)) + self.phase=3; self.moved=True; return a + self.pitch=float(np.clip(-.8+.018*(y-32),-1.5,-.2)) + self.yaw=float(np.clip(-.5-.025*(x-50),-1.3,.4)) + self.phase=2;self.start=t + return a + if self.phase==3: + dy=self.ygoal-float(obs['low_dim_obs'][19]) + if abs(dy)>.008: + a[1]=.15 if dy>0 else -.15 + else: + self.phase=1;self.wait=0 + return a + if self.phase==4: + self.wait+=1 + if self.wait<18: + return a + if float(obs['low_dim_obs'][18])=425 and not self.shifted: + self.xgoal=float(obs['low_dim_obs'][18])+.065 + self.phase=4; self.wait=0; self.shifted=True + return a + p=self.pitch; yaw=self.yaw + stage=elapsed//85 + if stage==1: p-=.08 + elif stage==2: p+=.08 + elif stage==3: p+=.16 + elif stage==4: p-=.16 + elif stage==5: yaw-=.12 + elif stage>=6: yaw+=.12 + a[4:8]=[p,-.15,yaw,1.0] + return a diff --git a/policies/reach_target_multi_modal/gpt61terra-s2/episodes.csv b/policies/reach_target_multi_modal/gpt61terra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..c44798e17613a05891044aa66f8f2ef8c5c50aa2 --- /dev/null +++ b/policies/reach_target_multi_modal/gpt61terra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,349,success,0 +620001,1,463,success,0 +620002,1,262,success,0 +620003,1,203,success,0 +620004,1,356,success,0 +620005,1,204,success,0 +620006,1,376,success,0 +620007,1,275,success,0 +620008,1,179,success,0 +620009,1,201,success,0 +620010,1,390,success,0 +620011,1,203,success,0 +620012,0,700,timeout,0 +620013,1,155,success,0 +620014,1,351,success,0 +620015,0,700,timeout,0 +620016,1,357,success,0 +620017,0,700,timeout,0 +620018,1,273,success,0 +620019,1,357,success,0 +620020,1,388,success,0 +620021,1,207,success,0 +620022,0,700,timeout,0 +620023,1,295,success,0 +620024,1,372,success,0 +620025,1,164,success,0 +620026,1,268,success,0 +620027,1,271,success,0 +620028,0,700,timeout,0 +620029,0,700,timeout,0 +620030,0,700,timeout,0 +620031,0,700,timeout,0 +620032,1,275,success,0 +620033,1,266,success,0 +620034,1,278,success,0 +620035,1,367,success,0 +620036,1,366,success,0 +620037,1,273,success,0 +620038,1,359,success,0 +620039,1,209,success,0 +620040,1,212,success,0 +620041,1,364,success,0 +620042,0,700,timeout,0 +620043,1,266,success,0 +620044,1,270,success,0 +620045,1,210,success,0 +620046,1,202,success,0 +620047,0,700,timeout,0 +620048,1,204,success,0 +620049,1,388,success,0 +620050,1,341,success,0 +620051,1,262,success,0 +620052,1,270,success,0 +620053,1,366,success,0 +620054,1,173,success,0 +620055,0,700,timeout,0 +620056,1,263,success,0 +620057,1,357,success,0 +620058,1,356,success,0 +620059,1,352,success,0 +620060,1,196,success,0 +620061,0,700,timeout,0 +620062,1,353,success,0 +620063,1,273,success,0 +620064,1,365,success,0 +620065,0,700,timeout,0 +620066,1,250,success,0 +620067,0,700,timeout,0 +620068,1,160,success,0 +620069,1,256,success,0 +620070,1,280,success,0 +620071,1,263,success,0 +620072,1,389,success,0 +620073,1,388,success,0 +620074,1,306,success,0 +620075,1,250,success,0 +620076,1,265,success,0 +620077,1,297,success,0 +620078,1,457,success,0 +620079,1,203,success,0 +620080,1,398,success,0 +620081,1,274,success,0 +620082,1,355,success,0 +620083,1,389,success,0 +620084,1,172,success,0 +620085,1,258,success,0 +620086,1,181,success,0 +620087,1,250,success,0 +620088,1,269,success,0 +620089,1,256,success,0 +620090,1,204,success,0 +620091,1,180,success,0 +620092,1,341,success,0 +620093,0,700,timeout,0 +620094,1,353,success,0 +620095,0,700,timeout,0 +620096,1,180,success,0 +620097,1,357,success,0 +620098,1,204,success,0 +620099,1,266,success,0 diff --git a/policies/reach_target_multi_modal/gpt61terra-s2/policy.py b/policies/reach_target_multi_modal/gpt61terra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d55d88aa44eb1b89439c3ba41900c81faf4522a6 --- /dev/null +++ b/policies/reach_target_multi_modal/gpt61terra-s2/policy.py @@ -0,0 +1,28 @@ +import numpy as np +import cv2 +class Policy: + def reset(self,obs,tools): + self.hold=tools.hold_action(); self.phase=0; self.side=0; self.goal_y=0; self.tm=0 + def act(self,obs,tools): + a=self.hold.copy(); t=obs['t']; q=obs['low_dim_obs'] + if t<40: + a[0]=.15; return a + if t<70:return a + if self.phase==0: + im=tools.image('head'); r=im[:,:,0].astype(np.int16); g=im[:,:,1].astype(np.int16); b=im[:,:,2].astype(np.int16) + mask=((r>55)&(r>g*1.5)&(r>b*1.5)&(r-g>35)).astype(np.uint8) + n,lab,st,c=cv2.connectedComponentsWithStats(mask) + x=c[1+np.argmax(st[1:,4]),0] if n>1 else 42 + self.side=1 if x>=42 else -1 + target=59 if self.side==1 else 25 + self.goal_y=q[19]+np.clip((target-x)*.009,-.10,.10); self.phase=1 + if self.phase==1: + err=self.goal_y-q[19] + if abs(err)>.025 and t<190: + a[1]=.16*np.sign(err); a[0]=np.clip((.02-q[18])*1.2,-.12,.12); a[3]=np.clip(-q[21]*1.5,-.2,.2) + return a + self.phase=2; self.tm=t + if self.phase==2 and t-self.tm<30:return a + poses=[(-.4,.3),(-.7,.6),(-.8,1),(-1,1.2),(-1.2,1.5),(-.2,0)] + i=min(int((t-self.tm-30)//95),len(poses)-1); p,e=poses[max(0,i)]; j=11 if self.side==1 else 4; a[j:j+4]=[p,0,0,e] + return a diff --git a/policies/reach_target_multi_modal/gpt61terra-s3/episodes.csv b/policies/reach_target_multi_modal/gpt61terra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f438744a174be7f59c3b0453ed7d5bd7847625e6 --- /dev/null +++ b/policies/reach_target_multi_modal/gpt61terra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,700,timeout,0 +620001,0,700,timeout,0 +620002,1,136,success,0 +620003,1,134,success,0 +620004,0,700,timeout,0 +620005,0,700,timeout,0 +620006,0,700,timeout,0 +620007,0,700,timeout,0 +620008,1,180,success,0 +620009,1,143,success,0 +620010,1,124,success,0 +620011,1,223,success,0 +620012,0,700,timeout,0 +620013,0,700,timeout,0 +620014,0,700,timeout,0 +620015,1,146,success,0 +620016,0,700,timeout,0 +620017,0,700,timeout,0 +620018,1,156,success,0 +620019,1,264,success,0 +620020,0,700,timeout,0 +620021,0,700,timeout,0 +620022,0,700,timeout,0 +620023,1,141,success,0 +620024,0,700,timeout,0 +620025,0,700,timeout,0 +620026,1,182,success,0 +620027,1,137,success,0 +620028,0,700,timeout,0 +620029,0,700,timeout,0 +620030,0,700,timeout,0 +620031,1,142,success,0 +620032,1,142,success,0 +620033,0,700,timeout,0 +620034,0,700,timeout,0 +620035,0,700,timeout,0 +620036,0,700,timeout,0 +620037,1,156,success,0 +620038,0,700,timeout,0 +620039,1,147,success,0 +620040,0,700,timeout,0 +620041,0,700,timeout,0 +620042,0,700,timeout,0 +620043,1,179,success,0 +620044,0,700,timeout,0 +620045,0,700,timeout,0 +620046,0,700,timeout,0 +620047,0,700,timeout,0 +620048,1,140,success,0 +620049,0,700,timeout,0 +620050,0,700,timeout,0 +620051,1,164,success,0 +620052,1,142,success,0 +620053,0,700,timeout,0 +620054,1,171,success,0 +620055,0,700,timeout,0 +620056,1,134,success,0 +620057,1,232,success,0 +620058,1,193,success,0 +620059,0,700,timeout,0 +620060,0,700,timeout,0 +620061,0,700,timeout,0 +620062,0,700,timeout,0 +620063,1,136,success,0 +620064,1,264,success,0 +620065,0,700,timeout,0 +620066,1,118,success,0 +620067,0,700,timeout,0 +620068,1,147,success,0 +620069,1,158,success,0 +620070,1,157,success,0 +620071,1,157,success,0 +620072,0,700,timeout,0 +620073,0,700,timeout,0 +620074,1,141,success,0 +620075,1,142,success,0 +620076,1,165,success,0 +620077,1,131,success,0 +620078,1,154,success,0 +620079,0,700,timeout,0 +620080,0,700,timeout,0 +620081,1,143,success,0 +620082,0,700,timeout,0 +620083,1,129,success,0 +620084,0,700,timeout,0 +620085,1,187,success,0 +620086,1,186,success,0 +620087,1,183,success,0 +620088,1,142,success,0 +620089,1,202,success,0 +620090,1,137,success,0 +620091,1,151,success,0 +620092,0,700,timeout,0 +620093,0,700,timeout,0 +620094,0,700,timeout,0 +620095,0,700,timeout,0 +620096,0,700,timeout,0 +620097,0,700,timeout,0 +620098,1,138,success,0 +620099,0,700,timeout,0 diff --git a/policies/reach_target_multi_modal/gpt61terra-s3/policy.py b/policies/reach_target_multi_modal/gpt61terra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..fcbab997acf1e4af3179f2611906354316703b2b --- /dev/null +++ b/policies/reach_target_multi_modal/gpt61terra-s3/policy.py @@ -0,0 +1,45 @@ +import numpy as np +import cv2 +class Policy: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action(),dtype=np.float32); self.phase=0; self.aim=None; self.good=0; self.pitch=-.35; self.elbow=.4; self.reach=0; self.lock=0; self.pose=None; self.mode=None + def act(self,obs,tools): + t=obs['t']; a=self.a.copy() + if self.phase==0: + if t%5==0: + im=tools.image('head'); hsv=cv2.cvtColor(im,cv2.COLOR_RGB2HSV) + mask=((hsv[:,:,0]<9)&(hsv[:,:,1]>130)&(hsv[:,:,2]>55)).astype(np.uint8) + n,lab,st,cen=cv2.connectedComponentsWithStats(mask) + if n>1: + i=1+np.argmax(st[1:,4]); x,y,w,h,area=st[i] + if area>=5: + cx=x+(w-1)*.5; cy=y+(h-1)*.5 + if y==0: cy=y+h-w*.5 + q=np.array([cx,cy,float(w)]); self.aim=q if self.aim is None else .65*self.aim+.35*q + if self.mode is None and self.aim is not None: self.mode = "low" if self.aim[1]>15 else "high" + if self.aim is None: a[0]=.13 + else: + ex=57-self.aim[0]; ed=(30-self.aim[1]) if self.mode=="low" else (17-self.aim[2]) + vx=np.clip((.013 if self.mode=="low" else .065)*ed,-.18,.2); vy=np.clip(.013*ex,-.2,.2) + if abs(ex)<3 and abs(ed)<(3 if self.mode=="low" else 1.2): self.good+=1 + else:self.good=0 + if self.good>=15 or t>260: + self.phase=1; self.reach=t + self.pitch=float(np.clip(-.35+.025*(self.aim[1]-30),-1.1,.15)) + self.elbow=float(np.clip(.4+.017*(30-self.aim[1]),0,1.2)) + if self.mode=="low": self.pitch=-.35; self.elbow=.4 + else: + if abs(vx)<.065: vx=0 + if abs(vy)<.065: vy=0 + a[0]=vx; a[1]=vy + if self.phase==1: + candidates=[(0,0),(-.12,.12),(.12,-.12),(-.08,-.17),(.08,.17),(0,.25),(0,-.25)] + i=min(max(0,(t-self.reach-30)//80),len(candidates)-1) + if self.lock<=0: + dp,de=candidates[i]; self.pose=[self.pitch+dp,0,0,self.elbow+de] + a[11:15]=self.pose + if t%5==0: + im=tools.image('head').astype(np.int16); red=(im[:,:,0]>220)&(im[:,:,0]>im[:,:,1]*2)&(im[:,:,0]>im[:,:,2]*2) + if red.sum()>8:self.lock=30 + else:self.lock=max(0,self.lock-5) + return a diff --git a/policies/reach_target_multi_modal/gpt6sol-s1/episodes.csv b/policies/reach_target_multi_modal/gpt6sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..2afd98468ee8122fede436b7c522ee425874ca61 --- /dev/null +++ b/policies/reach_target_multi_modal/gpt6sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,391,success,0 +620001,1,685,success,0 +620002,1,422,success,0 +620003,1,290,success,0 +620004,1,479,success,0 +620005,1,286,success,0 +620006,1,483,success,0 +620007,0,700,timeout,0 +620008,1,415,success,0 +620009,1,421,success,0 +620010,1,614,success,0 +620011,0,700,timeout,0 +620012,0,700,timeout,0 +620013,1,325,success,0 +620014,1,457,success,0 +620015,1,289,success,0 +620016,1,420,success,0 +620017,0,700,timeout,0 +620018,0,700,timeout,0 +620019,1,455,success,0 +620020,1,386,success,0 +620021,0,700,timeout,0 +620022,1,404,success,0 +620023,1,420,success,0 +620024,1,388,success,0 +620025,0,700,timeout,0 +620026,1,436,success,0 +620027,1,421,success,0 +620028,0,700,timeout,0 +620029,0,700,timeout,0 +620030,1,459,success,0 +620031,1,431,success,0 +620032,1,421,success,0 +620033,1,400,success,0 +620034,0,700,timeout,0 +620035,1,388,success,0 +620036,1,454,success,0 +620037,1,423,success,0 +620038,1,390,success,0 +620039,0,700,timeout,0 +620040,0,700,timeout,0 +620041,1,385,success,0 +620042,0,700,timeout,0 +620043,1,421,success,0 +620044,1,404,success,0 +620045,1,282,success,0 +620046,1,288,success,0 +620047,1,535,success,0 +620048,1,421,success,0 +620049,1,389,success,0 +620050,1,391,success,0 +620051,0,700,timeout,0 +620052,0,700,timeout,0 +620053,1,454,success,0 +620054,1,421,success,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,1,402,success,0 +620058,1,391,success,0 +620059,1,458,success,0 +620060,0,700,timeout,0 +620061,1,488,success,0 +620062,1,390,success,0 +620063,1,422,success,0 +620064,1,460,success,0 +620065,0,700,timeout,0 +620066,1,420,success,0 +620067,0,700,timeout,0 +620068,1,339,success,0 +620069,1,354,success,0 +620070,1,307,success,0 +620071,1,372,success,0 +620072,1,386,success,0 +620073,1,385,success,0 +620074,1,356,success,0 +620075,1,420,success,0 +620076,1,421,success,0 +620077,0,700,timeout,0 +620078,1,396,success,0 +620079,0,700,timeout,0 +620080,1,384,success,0 +620081,1,431,success,0 +620082,1,403,success,0 +620083,1,399,success,0 +620084,0,700,timeout,0 +620085,1,432,success,0 +620086,1,421,success,0 +620087,1,421,success,0 +620088,0,700,timeout,0 +620089,1,420,success,0 +620090,1,430,success,0 +620091,0,700,timeout,0 +620092,1,403,success,0 +620093,1,489,success,0 +620094,1,468,success,0 +620095,0,700,timeout,0 +620096,0,700,timeout,0 +620097,1,400,success,0 +620098,1,421,success,0 +620099,1,330,success,0 diff --git a/policies/reach_target_multi_modal/gpt6sol-s1/policy.py b/policies/reach_target_multi_modal/gpt6sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..cfbefacbe037cdff0468a17bf082d2acf19b1b89 --- /dev/null +++ b/policies/reach_target_multi_modal/gpt6sol-s1/policy.py @@ -0,0 +1,73 @@ +"""Deterministic red-sphere reaching controller.""" +import cv2 +import numpy as np + + +def ball(image): + rgb = image.astype(np.int16) + mask = ((rgb[:, :, 0] > 70) & + (rgb[:, :, 0] > 1.5 * rgb[:, :, 1]) & + (rgb[:, :, 0] > 1.5 * rgb[:, :, 2])).astype(np.uint8) + n, _, stats, centroids = cv2.connectedComponentsWithStats(mask) + if n < 2: + return None + i = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + if stats[i, cv2.CC_STAT_AREA] < 15: + return None + return (float(centroids[i, 0]), float(centroids[i, 1]), + int(stats[i, cv2.CC_STAT_AREA]), int(stats[i, cv2.CC_STAT_TOP]), + int(stats[i, cv2.CC_STAT_HEIGHT])) + + +class Policy: + def reset(self, obs, tools): + self.initial = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = 0 + self.phase_t = 0 + self.settled = 0 + self.target_base = None + self.prev_ball = None + + def act(self, obs, tools): + a = self.initial.copy() + a[18] = 0.0 + self.phase_t += 1 + if self.phase == 0: + b = ball(tools.image('head')) + if b is not None: + x, y, area, top, height = b + dx = x - 42.0 + if abs(dx) > 3: + a[1] = np.clip(-0.014 * dx, -0.22, 0.22) + if top <= 1 or area < 120: + a[0] = 0.22 + elif area > 170: + a[0] = -0.15 + if a[0] == 0 and a[1] == 0: + self.settled += 1 + else: + self.settled = 0 + if self.settled > 16 or self.phase_t > 165: + self.phase = 1 + self.phase_t = 0 + else: + a[0] = 0.2 + elif self.phase == 1: + a[4] = -1.0 + if self.phase_t > 35: + self.phase = 2 + self.phase_t = 0 + elif self.phase == 2: + a[4] = -1.0 + a[5] = -0.15 + a[7] = 1.3 + if self.phase_t > 30: + self.phase = 3 + self.phase_t = 0 + else: + pitches = [-1.5, -1.35, -1.2, -1.05, -0.9, -0.75, -0.9, -1.05] + i = min((self.phase_t - 1) // 68, len(pitches) - 1) + a[4] = pitches[i] + a[5] = -0.15 + a[7] = 1.3 + return a diff --git a/policies/reach_target_multi_modal/gpt6sol-s2/episodes.csv b/policies/reach_target_multi_modal/gpt6sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..6d6fe57b8e8028d8089f0c14fad0d4feea427769 --- /dev/null +++ b/policies/reach_target_multi_modal/gpt6sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,278,success,0 +620001,1,164,success,0 +620002,1,146,success,0 +620003,1,146,success,0 +620004,1,183,success,0 +620005,1,154,success,0 +620006,0,700,timeout,0 +620007,1,161,success,0 +620008,1,171,success,0 +620009,1,144,success,0 +620010,1,244,success,0 +620011,1,168,success,0 +620012,1,276,success,0 +620013,1,137,success,0 +620014,0,700,timeout,0 +620015,1,150,success,0 +620016,1,175,success,0 +620017,1,258,success,0 +620018,1,164,success,0 +620019,1,200,success,0 +620020,1,180,success,0 +620021,1,154,success,0 +620022,0,700,timeout,0 +620023,1,180,success,0 +620024,1,199,success,0 +620025,1,140,success,0 +620026,1,131,success,0 +620027,1,148,success,0 +620028,0,700,timeout,0 +620029,0,700,timeout,0 +620030,0,700,timeout,0 +620031,1,139,success,0 +620032,1,166,success,0 +620033,1,168,success,0 +620034,1,141,success,0 +620035,1,189,success,0 +620036,1,417,success,0 +620037,1,163,success,0 +620038,1,211,success,0 +620039,1,176,success,0 +620040,1,185,success,0 +620041,1,209,success,0 +620042,1,180,success,0 +620043,1,141,success,0 +620044,1,159,success,0 +620045,1,146,success,0 +620046,1,151,success,0 +620047,0,700,timeout,0 +620048,1,126,success,0 +620049,1,184,success,0 +620050,1,193,success,0 +620051,1,133,success,0 +620052,1,198,success,0 +620053,0,700,timeout,0 +620054,1,130,success,0 +620055,0,700,timeout,0 +620056,1,145,success,0 +620057,1,326,success,0 +620058,0,700,timeout,0 +620059,0,700,timeout,0 +620060,1,166,success,0 +620061,1,365,success,0 +620062,1,191,success,0 +620063,1,164,success,0 +620064,1,347,success,0 +620065,0,700,timeout,0 +620066,1,153,success,0 +620067,0,700,timeout,0 +620068,1,150,success,0 +620069,1,171,success,0 +620070,1,161,success,0 +620071,1,152,success,0 +620072,1,186,success,0 +620073,1,189,success,0 +620074,1,160,success,0 +620075,1,151,success,0 +620076,1,170,success,0 +620077,1,147,success,0 +620078,1,169,success,0 +620079,1,166,success,0 +620080,1,187,success,0 +620081,1,131,success,0 +620082,1,188,success,0 +620083,1,186,success,0 +620084,1,165,success,0 +620085,1,157,success,0 +620086,1,132,success,0 +620087,1,142,success,0 +620088,1,132,success,0 +620089,1,133,success,0 +620090,1,130,success,0 +620091,1,138,success,0 +620092,1,194,success,0 +620093,1,220,success,0 +620094,1,188,success,0 +620095,0,700,timeout,0 +620096,1,169,success,0 +620097,1,204,success,0 +620098,1,143,success,0 +620099,1,172,success,0 diff --git a/policies/reach_target_multi_modal/gpt6sol-s2/policy.py b/policies/reach_target_multi_modal/gpt6sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..da84087572cd895c035ff29921ef8ddd6ce0d9a4 --- /dev/null +++ b/policies/reach_target_multi_modal/gpt6sol-s2/policy.py @@ -0,0 +1,88 @@ +"""Your policy: fill in reset() and act(). + +Keep this file self-contained (helper modules next to it are fine). Available +libraries: numpy, scipy, OpenCV (cv2), pillow and the Python standard library; +nothing else is installed. + +Contract + reset(obs, tools) called once at the start of every episode + act(obs, tools) -> raw called every control step (50 Hz); must return 20 floats + + raw = [vx, vy, height, wz, left arm (7), right arm (7), left gripper, right gripper] + See docs/api.md for units, ranges and the observation keys. + tools.hold_action() -> raw action that holds the current pose + tools.image(camera, w, h) -> RGB array from head / left_wrist / right_wrist (84x84) + tools.render(camera, path) -> save a PNG for your own inspection + +Determinism: do not use wall-clock time; if you need randomness, seed it from +obs at reset (e.g. np.random.default_rng(int(obs["t"]) + 1)). +""" + +import numpy as np + + +class Policy: + """The control policy that is scored on the hidden seeds.""" + + def reset(self, obs, tools): + """Prepare for one episode. + + Args: + obs: The first observation. + tools: The tools described in docs/api.md. + """ + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.x = None + self.y = None + self.phase = 0 + self.area = None + self.reach_pitch = 0.0 + + def target(self, tools): + im = tools.image('head') + r = im[:, :, 0].astype(np.int16) + g = im[:, :, 1].astype(np.int16) + b = im[:, :, 2].astype(np.int16) + mask = (r > 85) & (r > 1.55 * g) & (r > 1.55 * b) + yy, xx = np.where(mask) + if len(xx) < 4: + return None + return float(xx.mean()), float(yy.mean()), len(xx) + + def act(self, obs, tools): + """Return the action for this control step. + + Args: + obs: The current observation. + tools: The tools described in docs/api.md. + + Returns: + The physical action. + """ + raw = self.hold.copy() + target = self.target(tools) + if target is not None: + x, y, area = target + if self.x is None: + self.x, self.y = x, y + self.area = area + else: + self.x = 0.75 * self.x + 0.25 * x + self.y = 0.75 * self.y + 0.25 * y + self.area = 0.75 * self.area + 0.25 * area + + if self.phase == 0: + if self.area is None or self.area < 190: + raw[0] = 0.15 + else: + self.phase = 1 + self.reach_pitch = float(np.clip((self.y - 44.0) / 85.0, -0.55, 0.4)) + if self.y >= 50.0: + self.reach_pitch += 0.1 + if self.x is not None: + error = self.x - 44.0 + if abs(error) > 2.0: + raw[1] = np.clip(-0.013 * error, -0.25, 0.25) + if self.phase == 1: + raw[4:11] = [self.reach_pitch, 0.0, -0.5, 0.0, 0.0, 0.0, 0.0] + return raw diff --git a/policies/reach_target_multi_modal/gpt6sol-s3/episodes.csv b/policies/reach_target_multi_modal/gpt6sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..74359370f068ea77a6ada8723f925683f23da5e7 --- /dev/null +++ b/policies/reach_target_multi_modal/gpt6sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,407,success,0 +620001,1,470,success,0 +620002,1,338,success,0 +620003,1,257,success,0 +620004,1,336,success,0 +620005,1,290,success,0 +620006,1,357,success,0 +620007,1,324,success,0 +620008,1,470,success,0 +620009,1,314,success,0 +620010,1,261,success,0 +620011,1,470,success,0 +620012,1,312,success,0 +620013,1,368,success,0 +620014,1,386,success,0 +620015,1,309,success,0 +620016,1,331,success,0 +620017,1,275,success,0 +620018,1,328,success,0 +620019,1,354,success,0 +620020,1,290,success,0 +620021,1,289,success,0 +620022,1,336,success,0 +620023,1,289,success,0 +620024,1,349,success,0 +620025,1,321,success,0 +620026,1,473,success,0 +620027,1,351,success,0 +620028,1,366,success,0 +620029,1,305,success,0 +620030,1,396,success,0 +620031,1,350,success,0 +620032,1,278,success,0 +620033,1,412,success,0 +620034,1,311,success,0 +620035,0,700,timeout,0 +620036,1,324,success,0 +620037,1,294,success,0 +620038,1,369,success,0 +620039,1,287,success,0 +620040,1,281,success,0 +620041,1,368,success,0 +620042,1,284,success,0 +620043,1,246,success,0 +620044,1,355,success,0 +620045,1,253,success,0 +620046,1,470,success,0 +620047,1,319,success,0 +620048,1,242,success,0 +620049,1,300,success,0 +620050,1,357,success,0 +620051,1,306,success,0 +620052,1,246,success,0 +620053,1,328,success,0 +620054,1,265,success,0 +620055,1,401,success,0 +620056,1,315,success,0 +620057,1,344,success,0 +620058,1,470,success,0 +620059,1,403,success,0 +620060,1,311,success,0 +620061,1,403,success,0 +620062,1,369,success,0 +620063,1,350,success,0 +620064,1,329,success,0 +620065,1,469,success,0 +620066,1,287,success,0 +620067,1,341,success,0 +620068,1,319,success,0 +620069,1,350,success,0 +620070,1,287,success,0 +620071,1,350,success,0 +620072,1,284,success,0 +620073,1,290,success,0 +620074,1,470,success,0 +620075,1,289,success,0 +620076,1,307,success,0 +620077,1,305,success,0 +620078,1,353,success,0 +620079,1,314,success,0 +620080,1,311,success,0 +620081,1,258,success,0 +620082,1,349,success,0 +620083,1,285,success,0 +620084,1,326,success,0 +620085,1,314,success,0 +620086,1,319,success,0 +620087,1,244,success,0 +620088,1,276,success,0 +620089,1,321,success,0 +620090,1,256,success,0 +620091,1,315,success,0 +620092,1,377,success,0 +620093,1,401,success,0 +620094,1,371,success,0 +620095,1,373,success,0 +620096,1,470,success,0 +620097,1,356,success,0 +620098,1,350,success,0 +620099,1,297,success,0 diff --git a/policies/reach_target_multi_modal/gpt6sol-s3/policy.py b/policies/reach_target_multi_modal/gpt6sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..4bf3e5a820316298d2e86d206e1431fe6ae6c6fd --- /dev/null +++ b/policies/reach_target_multi_modal/gpt6sol-s3/policy.py @@ -0,0 +1,98 @@ +"""Visual servo controller for touching the red target with the left hand.""" + +import numpy as np + + +def red_blob(image): + rgb = image.astype(np.int16) + red = (rgb[:, :, 0] > 75) & (rgb[:, :, 0] > 1.55 * rgb[:, :, 1]) & (rgb[:, :, 0] > 1.45 * rgb[:, :, 2]) + ys, xs = np.nonzero(red) + if len(xs) < 20: + return None + return float(xs.mean()), float(ys.mean()), len(xs) + + +class Policy: + def reset(self, obs, tools): + head = red_blob(tools.image('head')) + self.phase = 'align' if head is not None and head[2] >= 50 and abs(head[0] - 43) > 4 else 'reach' + self.align_end = None + self.reach_start = 0 + self.p = -0.35 + self.yaw = -0.36 + self.roll = 0.2 + self.start_x = float(obs['low_dim_obs'][18]) + self.start_y = float(obs['low_dim_obs'][19]) + self.start_yaw = float(obs['low_dim_obs'][21]) + self.last_blob = None + self.max_area = 0 + self.lost = 0 + self.special = None + + def act(self, obs, tools): + t = obs['t'] + if t >= 410: + self.roll = 0.0 + if t == 300 and self.p < -0.30 and self.max_area >= 3000: + self.special = (self.p, self.yaw) + if self.special is not None and 300 <= t < 480: + p0, yaw0 = self.special + raw = np.asarray(tools.hold_action(), dtype=np.float32) + raw[0:4] = [0, 0, 0.74, 0] + if t < 360: + raw[4:11] = [p0, 0.2, yaw0 - 0.06, 0, 0, 0, 0] + elif t < 420: + raw[4:11] = [p0, 0.2, yaw0 + 0.06, 0, 0, 0, 0] + else: + raw[4:11] = [p0 + 0.06, 0.2, yaw0, 0, 0, 0, 0] + raw[18] = 0.0 + self.p = float(raw[4]) + self.yaw = float(raw[6]) + return raw + if self.phase == 'align': + raw = np.asarray(tools.hold_action(), dtype=np.float32) + raw[0:4] = [0, 0, 0.74, 0] + if self.align_end is None: + if t % 4 == 0: + blob = red_blob(tools.image('head')) + if blob is not None: + error = 43.0 - blob[0] + if abs(error) < 2.5 or t > 175: + self.align_end = t + 20 + else: + self.align_command = float(np.sign(error) * 0.13) + if self.align_end is None: + raw[3] = getattr(self, 'align_command', 0.0) + if self.align_end is not None and t >= self.align_end: + self.phase = 'reach' + self.reach_start = t + self.start_x = float(obs['low_dim_obs'][18]) + self.start_y = float(obs['low_dim_obs'][19]) + self.start_yaw = float(obs['low_dim_obs'][21]) + else: + return raw + t -= self.reach_start + if t >= 28 and t % 4 == 0: + blob = red_blob(tools.image('left_wrist')) + if blob is not None: + x, y, area = blob + self.last_blob = blob + self.max_area = max(self.max_area, area) + self.lost = 0 + self.p = float(np.clip(self.p + 0.003 * (y - 55), -1.0, 0.85)) + self.yaw = float(np.clip(self.yaw + 0.0007 * (55 - x), -1.15, 0.3)) + else: + self.lost += 4 + + raw = np.asarray(tools.hold_action(), dtype=np.float32) + raw[0:4] = [0, 0, 0.74, 0] + raw[4:11] = [self.p, self.roll, self.yaw, 0, 0, 0, 0] + raw[18] = 0.0 + if t > 55 and self.max_area < 3300 and self.lost < 24: + body = obs['low_dim_obs'] + dx = float(body[18]) - self.start_x + dy = float(body[19]) - self.start_y + travel = dx * np.cos(self.start_yaw) + dy * np.sin(self.start_yaw) + if travel < 0.72: + raw[0] = 0.075 + return raw diff --git a/policies/reach_target_multi_modal/kimi31pro-s1/episodes.csv b/policies/reach_target_multi_modal/kimi31pro-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..6a4fd90e72ba754a3a317be82eca5898379b21dc --- /dev/null +++ b/policies/reach_target_multi_modal/kimi31pro-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,403,success,0 +620001,1,389,success,0 +620002,1,375,success,0 +620003,1,321,success,0 +620004,1,358,success,0 +620005,1,326,success,0 +620006,1,410,success,0 +620007,1,391,success,0 +620008,1,355,success,0 +620009,1,370,success,0 +620010,1,359,success,0 +620011,1,365,success,0 +620012,1,387,success,0 +620013,1,332,success,0 +620014,1,378,success,0 +620015,1,336,success,0 +620016,1,348,success,0 +620017,1,351,success,0 +620018,1,367,success,0 +620019,1,382,success,0 +620020,1,357,success,0 +620021,1,325,success,0 +620022,1,367,success,0 +620023,1,328,success,0 +620024,1,382,success,0 +620025,1,356,success,0 +620026,1,359,success,0 +620027,1,401,success,0 +620028,1,389,success,0 +620029,1,386,success,0 +620030,1,405,success,0 +620031,1,325,success,0 +620032,1,403,success,0 +620033,1,417,success,0 +620034,1,366,success,0 +620035,1,381,success,0 +620036,1,384,success,0 +620037,1,367,success,0 +620038,1,413,success,0 +620039,1,381,success,0 +620040,1,383,success,0 +620041,1,417,success,0 +620042,1,354,success,0 +620043,1,351,success,0 +620044,1,389,success,0 +620045,1,326,success,0 +620046,1,335,success,0 +620047,1,383,success,0 +620048,1,327,success,0 +620049,1,380,success,0 +620050,1,385,success,0 +620051,1,346,success,0 +620052,1,349,success,0 +620053,1,377,success,0 +620054,1,356,success,0 +620055,1,457,success,0 +620056,1,371,success,0 +620057,1,384,success,0 +620058,1,379,success,0 +620059,1,426,success,0 +620060,1,365,success,0 +620061,1,428,success,0 +620062,1,400,success,0 +620063,1,386,success,0 +620064,1,386,success,0 +620065,1,440,success,0 +620066,1,371,success,0 +620067,1,448,success,0 +620068,1,370,success,0 +620069,1,389,success,0 +620070,1,404,success,0 +620071,1,398,success,0 +620072,1,389,success,0 +620073,1,381,success,0 +620074,1,400,success,0 +620075,1,375,success,0 +620076,1,392,success,0 +620077,1,358,success,0 +620078,1,407,success,0 +620079,1,327,success,0 +620080,1,385,success,0 +620081,1,359,success,0 +620082,1,401,success,0 +620083,1,353,success,0 +620084,1,338,success,0 +620085,1,371,success,0 +620086,1,355,success,0 +620087,1,385,success,0 +620088,1,359,success,0 +620089,1,311,success,0 +620090,1,325,success,0 +620091,1,356,success,0 +620092,1,393,success,0 +620093,1,458,success,0 +620094,1,398,success,0 +620095,1,390,success,0 +620096,1,358,success,0 +620097,1,393,success,0 +620098,1,367,success,0 +620099,1,386,success,0 diff --git a/policies/reach_target_multi_modal/kimi31pro-s1/policy.py b/policies/reach_target_multi_modal/kimi31pro-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..043c61e50580eceb69678a8fa46612afb42ee060 --- /dev/null +++ b/policies/reach_target_multi_modal/kimi31pro-s1/policy.py @@ -0,0 +1,133 @@ +"""Deterministic vision-guided reaching policy for the Unitree G1. + +The head camera guides lateral walking. The left wrist camera provides the +local approach error, and the target's bright-red contact material is used to +switch from approaching to gentle contact tracking. All control is explicit +joint-space and base-velocity feedback; there are no learned components. +""" + +import cv2 +import numpy as np + + +def _red_target(image): + """Return centroid, area and equivalent diameter of the red sphere.""" + a = np.asarray(image, dtype=np.int16) + r, g, b = a[:, :, 0], a[:, :, 1], a[:, :, 2] + mask = ((r > 45) & (r > 1.45 * g) & (r > 1.35 * b) + & ((r - g) > 25)).astype(np.uint8) + count, _, stats, centers = cv2.connectedComponentsWithStats(mask, 8) + if count <= 1: + return None + index = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + area = int(stats[index, cv2.CC_STAT_AREA]) + u, v = centers[index] + return (float(u), float(v), area, + float(2.0 * np.sqrt(area / np.pi)), stats[index].tolist()) + + +def _contact_color(image): + """The sphere turns bright red while it is touching the robot.""" + a = np.asarray(image, dtype=np.int16) + r, g, b = a[:, :, 0], a[:, :, 1], a[:, :, 2] + mask = (r > 45) & (r > 1.45 * g) & (r > 1.35 * b) & ((r - g) > 25) + if np.count_nonzero(mask) < 15: + return False + return bool(np.mean(r[mask] > 200) > 0.2 and np.mean(r[mask]) > 170.0) + + +class Policy: + """Raise the left hand, approach using both cameras, and hold contact.""" + + def reset(self, obs, tools): + self.base = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.base[18:20] = 0.6 + self.start_q = self.base[4:11].copy() + self.raised_q = np.array( + [-0.65, 0.2, 0.0, 0.0, 0.0, 0.0, 0.0], dtype=np.float32) + self.final_q = np.array( + [-0.45, 0.2, 0.2, 0.1, 0.0, 0.0, -1.0], dtype=np.float32) + self.q_command = self.final_q.copy() + self.t = 0 + self.last_head = None + self.last_wrist = None + self.wrist_missing = 0 + self.contact = False + self.ever_contact = False + self.last_bright_t = -1000 + + def act(self, obs, tools): + t = self.t + if t < 40: + q = self.start_q + (self.raised_q - self.start_q) * min( + 1.0, (t + 1) / 30.0) + self.q_command = q.copy() + elif t < 100: + q = self.raised_q + (self.final_q - self.raised_q) * min( + 1.0, (t - 39) / 50.0) + self.q_command = q.copy() + else: + q = self.q_command.copy() + + head_image = tools.image("head") + wrist_image = tools.image("left_wrist") + head = _red_target(head_image) + wrist = _red_target(wrist_image) + if head is not None: + self.last_head = head + if wrist is not None: + if self.last_wrist is None: + self.last_wrist = wrist + else: + filtered = (0.55 * np.asarray(self.last_wrist[:4]) + + 0.45 * np.asarray(wrist[:4])) + self.last_wrist = tuple(filtered) + (wrist[4],) + self.wrist_missing = 0 + else: + self.wrist_missing += 1 + + action = self.base.copy() + action[4:11] = q + yaw = float(obs["low_dim_obs"][21]) + action[3] = np.clip(-1.5 * yaw, -0.3, 0.3) + + is_bright = _contact_color(head_image) or _contact_color(wrist_image) + if is_bright: + self.last_bright_t = t + if self.contact and t - self.last_bright_t > 60: + self.contact = False + + if t >= 125 and not self.contact: + if self.last_wrist is not None and self.wrist_missing < 25: + u, v = self.last_wrist[:2] + self.q_command[2] = np.clip( + self.q_command[2] + np.clip(-0.0018 * (u - 44.0), -0.008, 0.008), + -1.0, 1.0) + self.q_command[0] = np.clip( + self.q_command[0] + np.clip(0.0018 * (v - 44.0), -0.008, 0.008), + -1.2, 0.5) + action[0] = 0.04 if self.ever_contact else 0.08 + else: + action[0] = 0.0 + if self.last_head is not None: + vy = np.clip(0.012 * (43.0 - self.last_head[0]), -0.1, 0.1) + action[1] = vy if abs(vy) >= 0.055 else 0.0 + + if not self.contact and t > 100 and is_bright: + self.contact = True + self.ever_contact = True + action[0] = action[1] = action[3] = 0.0 + + if self.contact: + action[0] = action[1] = action[3] = 0.0 + if self.last_wrist is not None and self.wrist_missing < 25: + u, v = self.last_wrist[:2] + self.q_command[2] = np.clip( + self.q_command[2] + np.clip(-0.0008 * (u - 44.0), -0.004, 0.004), + -1.0, 1.0) + self.q_command[0] = np.clip( + self.q_command[0] + np.clip(0.0008 * (v - 44.0), -0.004, 0.004), + -1.2, 0.5) + + self.t += 1 + return np.asarray(action, dtype=np.float32) diff --git a/policies/reach_target_multi_modal/kimi31pro-s2/episodes.csv b/policies/reach_target_multi_modal/kimi31pro-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..a91f1ace30bd93717c8c3ee66518ca106bf0e56c --- /dev/null +++ b/policies/reach_target_multi_modal/kimi31pro-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,410,success,0 +620001,0,700,timeout,0 +620002,1,383,success,0 +620003,0,700,timeout,0 +620004,1,506,success,0 +620005,0,700,timeout,0 +620006,1,512,success,0 +620007,0,700,timeout,0 +620008,1,375,success,0 +620009,1,386,success,0 +620010,1,397,success,0 +620011,0,700,timeout,0 +620012,1,516,success,0 +620013,0,700,timeout,0 +620014,1,434,success,0 +620015,0,700,timeout,0 +620016,1,419,success,0 +620017,1,509,success,0 +620018,0,700,timeout,0 +620019,1,457,success,0 +620020,1,417,success,0 +620021,0,700,timeout,0 +620022,1,217,success,0 +620023,0,700,timeout,0 +620024,1,489,success,0 +620025,0,700,timeout,0 +620026,0,700,timeout,0 +620027,0,700,timeout,0 +620028,1,672,success,0 +620029,1,690,success,0 +620030,1,516,success,0 +620031,0,700,timeout,0 +620032,0,700,timeout,0 +620033,0,700,timeout,0 +620034,0,700,timeout,0 +620035,1,492,success,0 +620036,1,667,success,0 +620037,0,700,timeout,0 +620038,1,444,success,0 +620039,0,700,timeout,0 +620040,1,419,success,0 +620041,1,436,success,0 +620042,1,467,success,0 +620043,1,372,success,0 +620044,0,700,timeout,0 +620045,0,700,timeout,0 +620046,0,700,timeout,0 +620047,1,657,success,0 +620048,0,700,timeout,0 +620049,1,404,success,0 +620050,1,428,success,0 +620051,0,700,timeout,0 +620052,1,363,success,0 +620053,1,428,success,0 +620054,0,700,timeout,0 +620055,0,700,timeout,0 +620056,0,700,timeout,0 +620057,1,376,success,0 +620058,1,409,success,0 +620059,1,676,success,0 +620060,0,700,timeout,0 +620061,1,668,success,0 +620062,1,415,success,0 +620063,1,387,success,0 +620064,1,410,success,0 +620065,0,700,timeout,0 +620066,1,385,success,0 +620067,1,690,success,0 +620068,0,700,timeout,0 +620069,1,406,success,0 +620070,1,681,success,0 +620071,1,384,success,0 +620072,1,413,success,0 +620073,1,407,success,0 +620074,1,661,success,0 +620075,1,373,success,0 +620076,0,700,timeout,0 +620077,0,700,timeout,0 +620078,0,700,timeout,0 +620079,1,228,success,0 +620080,1,469,success,0 +620081,1,363,success,0 +620082,1,407,success,0 +620083,1,382,success,0 +620084,0,700,timeout,0 +620085,1,382,success,0 +620086,1,404,success,0 +620087,1,376,success,0 +620088,1,362,success,0 +620089,0,700,timeout,0 +620090,0,700,timeout,0 +620091,0,700,timeout,0 +620092,1,430,success,0 +620093,0,700,timeout,0 +620094,1,358,success,0 +620095,1,687,success,0 +620096,0,700,timeout,0 +620097,1,405,success,0 +620098,0,700,timeout,0 +620099,0,700,timeout,0 diff --git a/policies/reach_target_multi_modal/kimi31pro-s2/policy.py b/policies/reach_target_multi_modal/kimi31pro-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..09d400f00e659bfb6d6780fd453fdc47a64fdbc3 --- /dev/null +++ b/policies/reach_target_multi_modal/kimi31pro-s2/policy.py @@ -0,0 +1,134 @@ +"""Hand-written visual-reaching policy for the Unitree G1. + +The head camera supplies target bearings. The arm is raised clear of the +body, the base makes a slow centred approach, and then settles into a long +stationary hold (the touch condition must persist for 50 control steps). +""" + +import cv2 +import numpy as np + + +class Policy: + """Deterministic joint-space reaching controller with visual bearings.""" + + def reset(self, obs, tools): + low = np.asarray(obs["low_dim_obs"], dtype=np.float64) + self.yaw_reference = float(low[21]) + self.initial_yaw = self.yaw_reference + self.lateral_reference = None + initial_feature = self._red_features(tools.image("head")) + self.initial_area = (int(initial_feature[0][cv2.CC_STAT_AREA]) + if initial_feature is not None else 0) + initial_v = (float(initial_feature[1][1]) + if initial_feature is not None and self.initial_area >= 20 else -10.0) + self.high_target = (initial_v < 8.0 + or (self.initial_area >= 145 and initial_v < 13.0)) + self.final_pitch = -1.05 if self.high_target else -0.70 + self.arm_pitch = self.final_pitch + self.arm_yaw = -0.15 + self.stop_step = 300 if self.high_target else 600 + self.alignment_start = 305 + self.stop_height = 26.0 + self.secondary_end = 600 if (not self.high_target and self.initial_area < 115) else 580 + self.ready_count = 0 + self.head_u = 42.0 + self.head_v = 0.0 + self.last_head_step = -1000 + self.aligned_count = 0 + self.last_wrist_step = -1000 + self.vertical_search = 0 + self.horizontal_search = 0 + + @staticmethod + def _red_features(image): + """Return the largest red component as (stats, centroid), or None.""" + im = np.asarray(image, dtype=np.int16) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + mask = ((r > 70) & (r - np.maximum(g, b) > 30) + & (r > 1.25*g) & (r > 1.25*b)).astype(np.uint8) + n, labels, stats, centroids = cv2.connectedComponentsWithStats(mask, 8) + if n <= 1: + return None + j = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA]) + if stats[j, cv2.CC_STAT_AREA] < 3: + return None + return stats[j], centroids[j] + + def _remember_wrist(self, feature, t): + """Update deterministic search directions from a visible wrist target.""" + area = int(feature[0][cv2.CC_STAT_AREA]) + if area < 200: + return None + u, v = map(float, feature[1]) + self.last_wrist_step = t + self.vertical_search = 1 if v > 72.0 else (-1 if v < 12.0 else 0) + self.horizontal_search = 1 if u < 10.0 else (-1 if u > 74.0 else 0) + return u, v, area + + def act(self, obs, tools): + t = int(obs["t"]) + low = np.asarray(obs["low_dim_obs"], dtype=np.float64) + raw = np.zeros(20, dtype=np.float64) + raw[2] = 0.74 + + if t % 5 == 0 and t <= self.stop_step: + feature = self._red_features(tools.image("head")) + if feature is not None: + stats, centroid = feature + area = int(stats[cv2.CC_STAT_AREA]) + if area >= 20: + self.head_u, self.head_v = map(float, centroid) + self.last_head_step = t + if area >= 40: + update = np.clip(0.0025*(40.0-self.head_u), -0.025, 0.025) + self.yaw_reference = float(np.clip( + self.yaw_reference + update, + self.initial_yaw - 0.65, self.initial_yaw + 0.65)) + if t >= 290 and not self.high_target: + ready = (area >= 40 and self.head_v >= self.stop_height + and abs(self.head_u-40.0) < 18.0) + self.ready_count = self.ready_count + 1 if ready else 0 + if self.ready_count >= 2: + self.stop_step = t + + yaw_error = (self.yaw_reference - float(low[21]) + np.pi) % (2*np.pi) - np.pi + raw[3] = (np.clip(1.5*yaw_error, -0.25, 0.25) + if abs(yaw_error) > 0.012 else 0.0) + + if t == 220: + self.lateral_reference = float(low[19]) + if (220 <= t < self.stop_step) or (550 <= t < self.secondary_end): + raw[0] = 0.06 + if self.lateral_reference is not None: + raw[1] = np.clip(1.5*(self.lateral_reference-float(low[19])), -0.04, 0.04) + + # Centre the wrist after the base stops. Corrections pause while the + # target is centred and resume if settling changes the geometry. + aligning = (self.high_target and t >= self.alignment_start) or t >= 450 + if aligning and t % 5 == 0 and not (550 <= t < self.secondary_end): + feature = self._red_features(tools.image("left_wrist")) + measured = self._remember_wrist(feature, t) if feature is not None else None + if measured is not None and measured[2] >= 250: + u, v, _ = measured + aligned = abs(u-60.0) < 6.0 and abs(v-50.0) < 8.0 + self.aligned_count = self.aligned_count + 1 if aligned else 0 + if not aligned: + self.arm_yaw += float(np.clip(0.003*(60.0-u), -0.025, 0.025)) + self.arm_pitch += float(np.clip(0.002*(v-50.0), -0.020, 0.020)) + self.arm_yaw = float(np.clip(self.arm_yaw, -0.50, 0.40)) + self.arm_pitch = float(np.clip(self.arm_pitch, -1.35, -0.35)) + + if t < 40: + pitch = -1.5*(t+1)/40.0 + elif t < 130: + pitch = -1.5 + elif t < 170: + pitch = -1.5 + (self.final_pitch+1.5)*(t-129)/40.0 + else: + pitch = self.arm_pitch + shoulder_yaw = (self.arm_yaw*np.clip((t-39)/50.0, 0.0, 1.0) + if t < 90 else self.arm_yaw) + elbow = 0.8*np.clip((t-89)/40.0, 0.0, 1.0) + raw[4:11] = [pitch, 0.0, shoulder_yaw, elbow, 0.0, 0.0, 0.0] + return raw.astype(np.float32) diff --git a/policies/reach_target_multi_modal/kimi31pro-s3/episodes.csv b/policies/reach_target_multi_modal/kimi31pro-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..21d5fade95166dd3893284c4ddaf1260ec4a5528 --- /dev/null +++ b/policies/reach_target_multi_modal/kimi31pro-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,266,success,0 +620001,1,317,success,0 +620002,1,276,success,0 +620003,1,209,success,0 +620004,1,407,success,0 +620005,1,240,success,0 +620006,1,298,success,0 +620007,1,232,success,0 +620008,0,700,timeout,0 +620009,1,273,success,0 +620010,1,225,success,0 +620011,0,700,timeout,0 +620012,1,309,success,0 +620013,0,700,timeout,0 +620014,1,434,success,0 +620015,1,209,success,0 +620016,1,226,success,0 +620017,1,357,success,0 +620018,1,219,success,0 +620019,1,275,success,0 +620020,1,286,success,0 +620021,1,209,success,0 +620022,0,700,timeout,0 +620023,1,81,success,0 +620024,1,329,success,0 +620025,1,82,success,0 +620026,1,82,success,0 +620027,1,310,success,0 +620028,1,274,success,0 +620029,1,246,success,0 +620030,0,700,timeout,0 +620031,1,81,success,0 +620032,1,278,success,0 +620033,1,249,success,0 +620034,1,276,success,0 +620035,1,296,success,0 +620036,1,276,success,0 +620037,1,350,success,0 +620038,1,310,success,0 +620039,1,292,success,0 +620040,1,291,success,0 +620041,1,353,success,0 +620042,1,245,success,0 +620043,1,223,success,0 +620044,1,235,success,0 +620045,1,156,success,0 +620046,1,208,success,0 +620047,1,236,success,0 +620048,1,204,success,0 +620049,1,307,success,0 +620050,0,700,timeout,0 +620051,0,700,timeout,0 +620052,1,295,success,0 +620053,1,262,success,0 +620054,1,79,success,0 +620055,0,700,timeout,0 +620056,1,371,success,0 +620057,1,276,success,0 +620058,1,262,success,0 +620059,1,412,success,0 +620060,1,241,success,0 +620061,1,416,success,0 +620062,1,309,success,0 +620063,1,237,success,0 +620064,1,293,success,0 +620065,1,344,success,0 +620066,0,700,timeout,0 +620067,1,396,success,0 +620068,1,575,success,0 +620069,1,310,success,0 +620070,1,279,success,0 +620071,1,308,success,0 +620072,1,306,success,0 +620073,1,278,success,0 +620074,1,298,success,0 +620075,1,400,success,0 +620076,1,246,success,0 +620077,1,274,success,0 +620078,1,274,success,0 +620079,1,314,success,0 +620080,1,327,success,0 +620081,0,700,timeout,0 +620082,1,311,success,0 +620083,1,257,success,0 +620084,1,83,success,0 +620085,1,482,success,0 +620086,0,700,timeout,0 +620087,1,233,success,0 +620088,0,700,timeout,0 +620089,0,700,timeout,0 +620090,1,209,success,0 +620091,1,317,success,0 +620092,1,346,success,0 +620093,1,447,success,0 +620094,1,565,success,0 +620095,1,276,success,0 +620096,1,199,success,0 +620097,1,345,success,0 +620098,1,255,success,0 +620099,1,219,success,0 diff --git a/policies/reach_target_multi_modal/kimi31pro-s3/policy.py b/policies/reach_target_multi_modal/kimi31pro-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a22a9160a9c8594d1e8496225d6082cce588b14a --- /dev/null +++ b/policies/reach_target_multi_modal/kimi31pro-s3/policy.py @@ -0,0 +1,151 @@ +"""Deterministic visual reaching policy for the Unitree G1.""" + +import numpy as np + + +def _red_stats(image): + """Return centroid, pixel count, and mean red level for the sphere.""" + im = np.asarray(image, dtype=np.int16) + r, g, b = im[:, :, 0], im[:, :, 1], im[:, :, 2] + mask = (r > 55) & (r > 1.45 * g) & (r > 1.25 * b) + ys, xs = np.where(mask) + if len(xs) < 3: + return None + return np.array([xs.mean(), ys.mean()]), len(xs), float(r[mask].mean()) + + +class Policy: + def reset(self, obs, tools): + self.initial = np.asarray(tools.hold_action(), dtype=np.float64) + self.action = self.initial.copy() + self.target = self.initial.copy() + self.initial_pelvis = np.asarray(obs["low_dim_obs"][18:22], dtype=np.float64) + self.step = 0 + + # Pick the nearer hand and set a starting height from the head view. + head_stats = _red_stats(tools.image("head")) + if head_stats is not None: + head_x, head_y = head_stats[0] + else: + head_x, head_y = 43.0, -5.0 + self.left = True + self.arm = slice(4, 11) if self.left else slice(11, 18) + self.gripper = 18 if self.left else 19 + self.camera = "left_wrist" if self.left else "right_wrist" + self.sign = 1.0 if self.left else -1.0 + self.desired_x = 50.0 if self.left else 33.0 + self.target[self.gripper] = 0.0 + + pitch = float(np.clip(-1.3 + 0.025 * (head_y - 18.0), -1.8, -1.0)) + self.pre = np.array([pitch, 0.0, 0.3 * self.sign, 1.5, 0, 0, 0]) + self.pose = np.array([pitch, -0.3 * self.sign, 0.3 * self.sign, 1.5, 0, 0, 0]) + self.high_target = pitch < -1.55 + if self.high_target: + effective_x = head_x if self.left else 84.0 - head_x + start_yaw = self.sign * np.clip(0.3 + 0.035 * (effective_x - 43.0), -0.2, 1.0) + self.pre[2] = start_yaw + self.pose[2] = start_yaw + self.target[2] = 0.74 + self.stage_start = None + self.early = False + + self.approach = False + self.contact = False + self.contact_lost = 0 + self.contact_failures = 0 + self.seen_wrist = False + self.last_c = np.array([35.0, 49.0]) + + def _servo(self, cx, cy, gain): + self.pose[2] = np.clip( + self.pose[2] + gain * (cx - self.desired_x) / 42.0, -1.2, 1.2 + ) + vertical = gain * (cy - 45.0) / 42.0 + if self.high_target: + self.pose[3] = np.clip(self.pose[3] + 0.45 * vertical, 0.8, 2.05) + self.pose[0] = np.clip(self.pose[0] + 0.55 * vertical, -2.1, -0.55) + else: + self.pose[3] = np.clip(self.pose[3] + vertical, 0.8, 2.05) + + def act(self, obs, tools): + self.step += 1 + step = self.step + + # First raise the arm with zero roll, then add roll. This ordering avoids + # a torso-collision configuration that otherwise limits shoulder pitch. + if self.early and step <= 110: + self.action = self.target.copy() + self.action[self.arm] = self.pose + elif step <= 75: + self.target[self.arm] = self.pre + alpha = min(1.0, step / 60.0) + self.action = self.initial * (1.0 - alpha) + self.target * alpha + elif step <= 110: + if step == 76: + self.stage_start = self.action.copy() + self.target[self.arm] = self.pose + alpha = min(1.0, (step - 75) / 25.0) + self.action = self.stage_start * (1.0 - alpha) + self.target * alpha + else: + self.action = self.target.copy() + self.action[self.arm] = self.pose + if self.approach: + low = np.asarray(obs["low_dim_obs"], dtype=np.float64) + yaw = low[21] + dx = low[18] - self.initial_pelvis[0] + dy = low[19] - self.initial_pelvis[1] + left_error = -np.sin(yaw) * dx + np.cos(yaw) * dy + self.action[0] = 0.08 + self.action[1] = np.clip(-0.6 * left_error, -0.08, 0.08) + self.action[3] = np.clip( + -0.8 * (yaw - self.initial_pelvis[3]), -0.25, 0.25 + ) + + # Update visual state for the next control step. No simulator state other + # than the robot cameras and body observation is used. + head_stats = _red_stats(tools.image("head")) + wrist_stats = _red_stats(tools.image(self.camera)) + bright = max( + head_stats[2] if head_stats is not None else 0.0, + wrist_stats[2] if wrist_stats is not None else 0.0, + ) + if wrist_stats is not None: + self.seen_wrist = True + + if not self.contact and bright > 170.0: + if step <= 110: + self.early = True + self.pose = self.action[self.arm].copy() + self.contact = True + self.contact_lost = 0 + self.approach = False + elif self.contact: + if bright > 170.0: + self.contact_lost = 0 + else: + self.contact_lost += 1 + if self.contact_lost >= 5: + self.contact = False + self.contact_lost = 0 + self.approach = False + self.contact_failures += 1 + if self.contact and step % 5 == 0 and wrist_stats is not None: + self._servo(wrist_stats[0][0], wrist_stats[0][1], 0.03) + self.approach = bool( + self.contact + and (self.contact_failures > 0 or bright <= 170.0) + and wrist_stats is not None + and wrist_stats[0][1] < 72.0 + ) + elif self.early or step > 100: + if step % 5 == 0 and wrist_stats is not None: + self.last_c = wrist_stats[0].copy() + self._servo(self.last_c[0], self.last_c[1], 0.08) + self.approach = bool( + self.seen_wrist + and step > 120 + and wrist_stats is not None + and wrist_stats[0][1] < 72.0 + ) + + return np.asarray(self.action, dtype=np.float32) diff --git a/policies/reach_target_multi_modal/opus-s1/episodes.csv b/policies/reach_target_multi_modal/opus-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..994250f050eb125ef247099321918161bb46ac8c --- /dev/null +++ b/policies/reach_target_multi_modal/opus-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,234,success,0 +620001,1,240,success,0 +620002,1,269,success,0 +620003,1,300,success,0 +620004,1,260,success,0 +620005,1,270,success,0 +620006,1,221,success,0 +620007,1,230,success,0 +620008,1,227,success,0 +620009,1,275,success,0 +620010,1,296,success,0 +620011,1,234,success,0 +620012,1,260,success,0 +620013,1,239,success,0 +620014,1,231,success,0 +620015,1,238,success,0 +620016,1,227,success,0 +620017,1,292,success,0 +620018,1,236,success,0 +620019,1,224,success,0 +620020,1,293,success,0 +620021,1,270,success,0 +620022,1,233,success,0 +620023,1,238,success,0 +620024,1,234,success,0 +620025,1,228,success,0 +620026,1,234,success,0 +620027,1,271,success,0 +620028,1,255,success,0 +620029,1,288,success,0 +620030,1,226,success,0 +620031,1,238,success,0 +620032,1,249,success,0 +620033,1,238,success,0 +620034,1,268,success,0 +620035,1,230,success,0 +620036,1,224,success,0 +620037,1,237,success,0 +620038,1,236,success,0 +620039,1,297,success,0 +620040,1,297,success,0 +620041,1,263,success,0 +620042,1,267,success,0 +620043,1,240,success,0 +620044,1,232,success,0 +620045,1,298,success,0 +620046,1,268,success,0 +620047,1,222,success,0 +620048,1,237,success,0 +620049,1,234,success,0 +620050,1,232,success,0 +620051,1,236,success,0 +620052,1,243,success,0 +620053,1,226,success,0 +620054,1,234,success,0 +620055,1,252,success,0 +620056,1,268,success,0 +620057,1,263,success,0 +620058,1,224,success,0 +620059,1,255,success,0 +620060,1,264,success,0 +620061,1,256,success,0 +620062,1,260,success,0 +620063,1,240,success,0 +620064,1,228,success,0 +620065,1,223,success,0 +620066,1,269,success,0 +620067,1,289,success,0 +620068,1,235,success,0 +620069,1,244,success,0 +620070,1,243,success,0 +620071,1,269,success,0 +620072,1,295,success,0 +620073,1,293,success,0 +620074,1,242,success,0 +620075,1,269,success,0 +620076,1,246,success,0 +620077,1,301,success,0 +620078,1,237,success,0 +620079,1,265,success,0 +620080,1,297,success,0 +620081,1,241,success,0 +620082,1,262,success,0 +620083,1,295,success,0 +620084,1,227,success,0 +620085,1,268,success,0 +620086,1,232,success,0 +620087,1,245,success,0 +620088,1,239,success,0 +620089,1,231,success,0 +620090,1,239,success,0 +620091,1,232,success,0 +620092,1,261,success,0 +620093,1,255,success,0 +620094,1,259,success,0 +620095,1,255,success,0 +620096,1,227,success,0 +620097,1,263,success,0 +620098,1,275,success,0 +620099,1,235,success,0 diff --git a/policies/reach_target_multi_modal/opus-s1/policy.py b/policies/reach_target_multi_modal/opus-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b88d5fe6e9ea835762c7653d103b936034948737 --- /dev/null +++ b/policies/reach_target_multi_modal/opus-s1/policy.py @@ -0,0 +1,514 @@ +"""Touch the red sphere with either hand (Unitree G1). + +Pipeline (all hand-written geometry, no learned parts): + 1. Tuck the arms, stand still. + 2. Calibrate the head camera from the 0.2 m floor checkerboard (fit the camera + pose so a synthetic checkerboard matches the image) and locate the sphere in + world coordinates: its shadow (light from straight above) gives x, y; the + sphere's ray intersected with the vertical line above the shadow gives z. + 3. Walk (closed loop on the pelvis odometry) until the sphere is a comfortable + distance ahead. + 4. Reach with the nearer arm: inverse kinematics of the G1 arm so the fingers + point at the sphere with the finger tips slightly inside it; the torso lean is + re-measured from the camera and the arm target is refined until the sphere + lights up (touched), then held. +""" + +import cv2 # noqa: F401 +import numpy as np +import scipy.ndimage as nd +from scipy.optimize import least_squares + +# ----------------------------------------------------------------------------- geometry +SQ = 0.2 # floor checker square (m) +RS = 0.05 # sphere radius (m) +F_PIX = 72.75 # head camera focal length in pixels (fovy 60 deg, 84 px) +TUCK = np.array([0.2, 0.25, 0.0, 1.4, 0.0, 0.0, 0.0]) +MIRROR = np.array([1, -1, -1, 1, -1, 1, -1]) + + +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.054]) +_ROT = {'x': rx, 'y': ry, 'z': rz} + + +def _specs(side): + s = 1 if side == 'L' else -1 + return [((0.0039563, s * 0.10022, 0.24778), rpy(s * 0.27931, 5.4949e-05, -s * 0.00019159), 'y'), + ((0, s * 0.038, -0.013831), rx(-s * 0.27925), 'x'), + ((0, s * 0.00624, -0.1032), np.eye(3), 'z'), + ((0.015783, 0, -0.080518), np.eye(3), 'y'), + ((0.100, s * 0.00188791, -0.010), np.eye(3), 'x'), + ((0.038, 0, 0), np.eye(3), 'y'), + ((0.046, 0, 0), np.eye(3), 'z')] + + +SPECS = {'L': _specs('L'), 'R': _specs('R')} + + +def hand_pose(q, side): + """Wrist-yaw link pose (position, rotation) in the (upright) pelvis frame.""" + p = TORSO.copy() + R = np.eye(3) + for (off, R0, ax), qi in zip(SPECS[side], q): + p = p + R @ np.array(off) + R = R @ R0 @ _ROT[ax](qi) + return p, R + + +def shoulder_pos(side): + off, R0, _ = SPECS[side][0] + return TORSO + np.array(off) + + +# ----------------------------------------------------------------------------- camera +def cam_axes(yaw, pitch, roll): + F = np.array([np.cos(pitch) * np.cos(yaw), np.cos(pitch) * np.sin(yaw), -np.sin(pitch)]) + R0 = np.array([np.sin(yaw), -np.cos(yaw), 0.0]) + U0 = np.cross(R0, F) + c, s = np.cos(roll), np.sin(roll) + return F, c * R0 + s * U0, -s * R0 + c * U0 + + +def pix_rays(par, us, vs): + cx, cy, cz, yaw, pitch, roll, f = par + F, R, U = cam_axes(yaw, pitch, roll) + d = F[None] + ((us - 42) / f)[:, None] * R[None] - ((vs - 42) / f)[:, None] * U[None] + return np.array([cx, cy, cz]), d + + +def floor_mask(im): + im = im.astype(int) + r, b = im[..., 0], im[..., 2] + return nd.binary_erosion((b - r > 35) & (b > 100), iterations=1) + + +def obs_signal(im): + b = im[..., 2].astype(float) + mu = nd.uniform_filter(b, 9) + sd = np.sqrt(np.maximum(nd.uniform_filter(b * b, 9) - mu * mu, 1)) + return np.clip((b - mu) / sd, -1.5, 1.5) + + +def fit_checker(im, par0, signs=(1, -1)): + m = floor_mask(im) + m[:3] = False + vs, us = np.nonzero(m) + us = us + 0.5 + vs = vs + 0.5 + o = obs_signal(im)[m] / 1.2 + best = None + for sg in signs: + def res(p): + C, d = pix_rays(p, us, vs) + t = -C[2] / d[:, 2] + X = C[0] + t * d[:, 0] + Y = C[1] + t * d[:, 1] + r = sg * np.tanh(3.0 * np.sin(np.pi * X / SQ) * np.sin(np.pi * Y / SQ)) - o + r[t < 0] = 2 + return r + sol = least_squares(res, par0, x_scale=[0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 5], loss='soft_l1') + c = np.mean(sol.fun ** 2) + if best is None or c < best[0]: + best = (c, sol.x, sg) + return best + + +def fit_camera(im, pel, warm=None): + px, py, pz, pyaw = pel + if warm is not None: + starts = [warm] + else: + starts = [np.array([px + 0.12 * np.cos(pyaw) + dx, py + 0.12 * np.sin(pyaw), 1.16, pyaw, 1.08, 0, F_PIX]) + for dx in (-0.07, 0.0, 0.07)] + best = None + for p0 in starts: + c, p, sg = fit_checker(im, p0) + if best is None or c < best[0]: + best = (c, p, sg) + c, p, sg = best + # the checker is periodic: put the camera where the body says it must be + fwd_exp = 0.104 + 0.42 * (p[4] - 1.047) + p[0] -= SQ * np.round((p[0] - px - np.cos(pyaw) * fwd_exp) / SQ) + p[1] -= SQ * np.round((p[1] - py - np.sin(pyaw) * fwd_exp) / SQ) + return p, c + + +def floor_point(par, u, v): + C, d = pix_rays(par, np.array([u]), np.array([v])) + t = -C[2] / d[0, 2] + return C + t * d[0] + + +def unit_ray(par, u, v): + _, d = pix_rays(par, np.array([u]), np.array([v])) + return d[0] / np.linalg.norm(d[0]) + + +# ----------------------------------------------------------------------------- detection +def sphere_mask(im): + im = im.astype(int) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + return (r > g + 30) & (r > b + 25) + + +def bright_count(im): + im = im.astype(int) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + return int(((r > 200) & (g < 90) & (b < 90)).sum()) + + +def find_sphere(im): + m = sphere_mask(im) + if m.sum() < 3: + return None + lab, n = nd.label(m) + sizes = nd.sum(m, lab, range(1, n + 1)) + k = np.argmax(sizes) + 1 + ys, xs = np.nonzero(lab == k) + return dict(u=xs.mean() + 0.5, v=ys.mean() + 0.5, area=len(ys), top=ys.min(), bot=ys.max() + 1, + left=xs.min(), right=xs.max() + 1) + + +def shadow_candidates(im, vmin=15): + imf = im.astype(float) + r, b = imf[..., 0], imf[..., 2] + floorish = (b - r > 25) & ~sphere_mask(im) + bm = nd.maximum_filter(np.where(floorish, b, 0), size=9) + m = floorish & (b < 0.68 * bm) + m[:vmin] = False + m = nd.binary_opening(m, iterations=1) + lab, n = nd.label(m) + out = [] + for k in range(1, n + 1): + ys, xs = np.nonzero(lab == k) + a = len(ys) + if a < 4: + continue + h = ys.max() - ys.min() + 1 + w = xs.max() - xs.min() + 1 + out.append(dict(u=xs.mean() + 0.5, v=ys.mean() + 0.5, area=a, fill=a / (h * w), + touch_edge=bool(ys.max() >= 83 or xs.min() <= 0 or xs.max() >= 83))) + return out + + +def locate_sphere(im, par): + """Sphere centre in world coordinates, or None.""" + s = find_sphere(im) + if s is None: + return None + C = np.array(par[:3]) + full = s['top'] > 0 and s['bot'] < 84 and s['left'] > 0 and s['right'] < 84 + uc = (s['left'] + s['right']) / 2 if (s['left'] > 0 and s['right'] < 84) else s['u'] + vref = s['v'] if full else s['bot'] - 0.5 + if not full and s['bot'] <= 1: + return None + rdir = unit_ray(par, uc, vref) + hdir = rdir[:2] / np.linalg.norm(rdir[:2]) + best = None + for c in shadow_candidates(im): + if c['touch_edge'] or c['v'] > 76 or c['fill'] < 0.4 or c['v'] < vref: + continue + F = floor_point(par, c['u'], c['v']) + w = F[:2] - C[:2] + if np.dot(w, hdir) < 0: + continue + miss = abs(hdir[0] * w[1] - hdir[1] * w[0]) + (0.03 if c['area'] < 6 else 0) + if best is None or miss < best[0]: + best = (miss, F) + if best is None or best[0] > 0.06: + return None + F = best[1] + t = np.dot(F[:2] - C[:2], rdir[:2]) / np.dot(rdir[:2], rdir[:2]) + z = (C + t * rdir)[2] + if not full: + z += RS / np.linalg.norm(rdir[:2]) + return np.array([F[0], F[1], z]) + + +def locate_sphere_size(im, par): + """Sphere centre from its apparent size (fallback, needs the whole disc).""" + s = find_sphere(im) + if s is None or not (s['top'] > 0 and s['bot'] < 84 and s['left'] > 0 and s['right'] < 84): + return None + rdir = unit_ray(par, s['u'], s['v']) + rpx = np.sqrt(s['area'] / np.pi) + return np.array(par[:3]) + RS * par[6] / rpx * rdir + + +# ----------------------------------------------------------------------------- IK +TIP = np.array([0.15, 0.0, 0.0]) +NOMINAL = {'L': np.array([-0.3, 0.05, 0.0, 0.3, 0, 0, 0]), 'R': np.array([-0.3, -0.05, 0.0, 0.3, 0, 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 joint_limits(side): + lo = LO.copy() + hi = HI.copy() + lo[1] = -0.1 # never swing the upper arm into the torso + if side == 'L': + return lo, hi + return lo * MIRROR + (hi * MIRROR - lo * MIRROR) * (MIRROR < 0), hi * MIRROR + (lo * MIRROR - hi * MIRROR) * (MIRROR < 0) + + +SEARCH_OFFSETS = [np.array(v) for v in ((0, 0, 0.02), (0, 0, -0.02), (0, 0.02, 0), (0, -0.02, 0), + (0.02, 0, 0.03), (0, 0, 0))] + + +def approach_dir(Sb, side): + """Finger direction for reaching the sphere at Sb (upright pelvis frame).""" + sh = shoulder_pos(side) + h = Sb[:2] - sh[:2] + h = h / np.linalg.norm(h) + dz = np.clip((Sb[2] - sh[2]) / 0.45, -0.9, 0.3) + d = np.array([h[0], h[1], dz]) + return d / np.linalg.norm(d) + + +def solve_ik(side, target, direction, q0, iters=60): + q, res = _solve_ik(side, target, direction, q0, iters, 0.03) + if res > 0.004: + q, res = _solve_ik(side, target, direction, q, iters, 0.0) + return q, res + + +def _solve_ik(side, target, direction, q0, iters, wdir): + """Tip at target (upright pelvis frame), finger axis along direction.""" + lo, hi = joint_limits(side) + q = q0.copy() + nom = NOMINAL[side] + for _ in range(iters): + def err(qq): + p, R = hand_pose(qq, side) + tip = p + R @ TIP + return np.concatenate([tip - target, wdir * (R[:, 0] - direction)]) + e = err(q) + J = np.zeros((6, 7)) + for j in range(7): + dq = np.zeros(7) + dq[j] = 1e-4 + J[:, j] = (err(q + dq) - e) / 1e-4 + lam = 1e-3 + W = np.diag([0.02, 0.02, 0.02, 0.02, 0.5, 0.5, 0.5]) + A = J.T @ J + lam * np.eye(7) + W * 0.001 + g = J.T @ e + (W * 0.001) @ (q - nom) + q = np.clip(q - np.linalg.solve(A, g), lo + 0.02, hi - 0.02) + p, R = hand_pose(q, side) + return q, np.linalg.norm(p + R @ TIP - target) + + +# ----------------------------------------------------------------------------- policy +class Policy: + """The control policy that is scored on the hidden seeds.""" + + STAND_X = 0.34 # desired sphere position relative to the pelvis (m) + STAND_Y = 0.13 # (in front of the reaching shoulder) + GRIP = 1.0 # reaching gripper closed: the fingers form one blunt tip + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = 'tuck' + self.t_phase = 0 + self.cam = None + self.S = None + self.side = None + self.q_cmd = None + self.q_goal = None + self.beta = 0.05 + self.depth = 0.02 + self.touch_steps = 0 + self.t_reach = 0 + self.last_counts = None + self.yaw0 = float(obs['low_dim_obs'][21]) + self.log = [] + + # -- helpers + def _pel(self, obs): + return np.asarray(obs['low_dim_obs'][18:22], dtype=float) + + def _arm_action(self, raw, qL, qR): + raw[4:11] = qL + raw[11:18] = qR + return raw + + def _to_body(self, P, pel): + """World point -> upright pelvis frame (yaw only), then undo torso lean.""" + d = P - np.array([pel[0], pel[1], pel[2]]) + d = rz(-pel[3]) @ d + return ry(-self.beta) @ d + + def _goal(self, pel): + side = self.side + Sb = self._to_body(self.S, pel) + if self.t_reach >= 120: + # still no touch: probe small offsets around the estimate + k = (self.t_reach - 120) // 40 + Sb = Sb + SEARCH_OFFSETS[k % len(SEARCH_OFFSETS)] + dirn = approach_dir(Sb, side) + target = Sb - dirn * (RS - self.depth) + q0 = self.q_goal if self.q_goal is not None else NOMINAL[side] + q, res = solve_ik(side, target, dirn, q0) + return q, res + + def _locate(self, tools, pel, warm=None): + im = tools.image('head') + par, c = fit_camera(im, pel, warm) + S = locate_sphere(im, par) + return im, par, c, S + + # -- main + def act(self, obs, tools): + try: + raw = self._act(obs, tools) + self.last_raw = raw + return raw + except Exception as exc: # never crash the episode: keep the last command + self.log.append(('error', int(obs['t']), repr(exc))) + raw = getattr(self, 'last_raw', None) + if raw is None: + raw = self.hold.copy() + raw = np.array(raw, dtype=np.float32) + raw[0:2] = 0.0 + raw[3] = 0.0 + return raw + + def _act(self, obs, tools): + raw = self.hold.copy() + pel = self._pel(obs) + self.t_phase += 1 + tuckL = TUCK + tuckR = TUCK * MIRROR + ph = self.phase + + if ph == 'tuck': + a = min(1.0, self.t_phase / 20) + self._arm_action(raw, a * tuckL, a * tuckR) + if self.t_phase >= 40: + im, par, c, S = self._locate(tools, pel) + self.cam = par + if S is None: + S = locate_sphere_size(im, par) + self.S = S + self.log.append(('look', obs['t'], None if S is None else S.tolist(), float(c))) + if S is None: + self.phase = 'search' + else: + self.phase = 'walk' + self.t_phase = 0 + return raw + + self._arm_action(raw, tuckL, tuckR) + + if ph == 'search': + # sphere not located (e.g. above the view): creep forward, which + # brings anything below the camera down into the image, and look again + raw[0] = 0.1 if self.t_phase < 150 else -0.1 + if self.t_phase % 25 == 0: + im, par, c, S = self._locate(tools, pel) + if S is None: + S = locate_sphere_size(im, par) + if S is not None: + self.S = S + self.phase = 'walk' + self.t_phase = 0 + return raw + + if ph == 'walk': + if self.side is None: + d0 = rz(-pel[3]) @ (self.S - np.array([pel[0], pel[1], 0])) + self.side = 'L' if d0[1] >= 0 else 'R' + d = rz(-pel[3]) @ (self.S - np.array([pel[0], pel[1], 0])) + ex = d[0] - self.STAND_X + ey = d[1] - (self.STAND_Y if self.side == 'L' else -self.STAND_Y) + yaw_err = np.arctan2(np.sin(pel[3] - self.yaw0), np.cos(pel[3] - self.yaw0)) + raw[3] = float(np.clip(-2.0 * yaw_err, -0.3, 0.3)) + if np.hypot(ex, ey) < 0.015 or self.t_phase > 300: + raw[0] = 0.0 + raw[1] = 0.0 + raw[3] = 0.0 + self.phase = 'settle' + self.t_phase = 0 + else: + v = np.clip(1.2 * np.array([ex, ey]), -0.2, 0.2) + sp = np.linalg.norm(v) + if sp < 0.07: + v = v * (0.07 / sp) + raw[0] = float(v[0]) + raw[1] = float(v[1]) + return raw + + if ph == 'settle': + if self.t_phase >= 25: + im, par, c, S = self._locate(tools, pel, warm=None) + self.cam = par + if S is not None and np.linalg.norm(S - self.S) < 0.08: + self.S = 0.5 * (S + self.S) + self.log.append(('settle', obs['t'], None if S is None else S.tolist(), float(c))) + self.beta = par[4] - 1.047 + self.q_start = np.array(TUCK if self.side == 'L' else TUCK * MIRROR) + self.q_goal, res = self._goal(pel) + self.q_cmd = self.q_start.copy() + self.phase = 'reach' + self.t_phase = 0 + return raw + + # reach / hold phases: one arm moves, the other stays tucked + if ph in ('reach', 'hold'): + if self.t_phase % 5 == 0: + self.q_goal, res = self._goal(pel) + step = 0.04 if ph == 'reach' else 0.01 + dq = self.q_goal - self.q_cmd + n = np.max(np.abs(dq)) + self.q_cmd = self.q_goal.copy() if n <= step else self.q_cmd + dq * (step / n) + if ph == 'reach': + self.t_reach = getattr(self, 't_reach', 0) + 1 + if self.t_reach % 20 == 0 and self.t_reach >= 40: + im = tools.image('head') + par, c = fit_camera(im, pel, warm=self.cam) + if c < 0.35: + self.cam = par + self.beta = par[4] - 1.047 + S = locate_sphere(im, par) + self.log.append(('reach', obs['t'], None if S is None else np.round(S, 3).tolist(), round(float(c), 3), round(self.beta, 3))) + if self.t_reach % 60 == 0: + self.depth = min(self.depth + 0.015, 0.06) + touched = self._touched(tools) + if touched: + self.touch_steps += 1 + self.phase = 'hold' + elif ph == 'hold': + self.touch_steps = 0 + self.phase = 'reach' + if self.side == 'L': + self._arm_action(raw, self.q_cmd, tuckR) + raw[18] = self.GRIP + else: + self._arm_action(raw, tuckL, self.q_cmd) + raw[19] = self.GRIP + return raw + + def _touched(self, tools): + n = bright_count(tools.image('head')) + cam = 'left_wrist' if self.side == 'L' else 'right_wrist' + m = bright_count(tools.image(cam)) + self.last_counts = (n, m) + return n >= 4 or m >= 15 diff --git a/policies/reach_target_multi_modal/opus-s2/episodes.csv b/policies/reach_target_multi_modal/opus-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..bb60c6c6605c9e7b5487950a77bfba38c506760e --- /dev/null +++ b/policies/reach_target_multi_modal/opus-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,275,success,0 +620001,1,277,success,0 +620002,1,270,success,0 +620003,1,258,success,0 +620004,1,265,success,0 +620005,1,257,success,0 +620006,1,280,success,0 +620007,1,271,success,0 +620008,1,263,success,0 +620009,1,268,success,0 +620010,1,257,success,0 +620011,1,268,success,0 +620012,1,273,success,0 +620013,1,261,success,0 +620014,1,273,success,0 +620015,1,255,success,0 +620016,1,265,success,0 +620017,1,259,success,0 +620018,1,267,success,0 +620019,1,275,success,0 +620020,1,267,success,0 +620021,1,255,success,0 +620022,1,263,success,0 +620023,1,238,success,0 +620024,1,275,success,0 +620025,1,261,success,0 +620026,1,250,success,0 +620027,1,317,success,0 +620028,1,269,success,0 +620029,1,264,success,0 +620030,1,278,success,0 +620031,1,230,success,0 +620032,1,372,success,0 +620033,1,281,success,0 +620034,1,266,success,0 +620035,1,273,success,0 +620036,1,271,success,0 +620037,1,266,success,0 +620038,1,280,success,0 +620039,1,268,success,0 +620040,1,264,success,0 +620041,1,279,success,0 +620042,1,263,success,0 +620043,1,298,success,0 +620044,1,275,success,0 +620045,1,250,success,0 +620046,1,254,success,0 +620047,1,265,success,0 +620048,1,249,success,0 +620049,1,263,success,0 +620050,1,272,success,0 +620051,1,239,success,0 +620052,1,313,success,0 +620053,1,267,success,0 +620054,1,256,success,0 +620055,1,288,success,0 +620056,1,267,success,0 +620057,1,266,success,0 +620058,1,272,success,0 +620059,1,284,success,0 +620060,1,261,success,0 +620061,1,287,success,0 +620062,1,272,success,0 +620063,1,275,success,0 +620064,1,272,success,0 +620065,1,284,success,0 +620066,1,346,success,0 +620067,1,295,success,0 +620068,1,267,success,0 +620069,1,286,success,0 +620070,1,326,success,0 +620071,1,284,success,0 +620072,1,266,success,0 +620073,1,268,success,0 +620074,1,280,success,0 +620075,1,268,success,0 +620076,1,323,success,0 +620077,1,294,success,0 +620078,1,278,success,0 +620079,1,257,success,0 +620080,1,273,success,0 +620081,1,320,success,0 +620082,1,274,success,0 +620083,1,263,success,0 +620084,1,258,success,0 +620085,1,320,success,0 +620086,1,258,success,0 +620087,1,304,success,0 +620088,1,260,success,0 +620089,1,241,success,0 +620090,1,262,success,0 +620091,1,263,success,0 +620092,1,278,success,0 +620093,1,290,success,0 +620094,1,270,success,0 +620095,1,270,success,0 +620096,1,263,success,0 +620097,1,277,success,0 +620098,1,297,success,0 +620099,1,275,success,0 diff --git a/policies/reach_target_multi_modal/opus-s2/policy.py b/policies/reach_target_multi_modal/opus-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a79508faa85c3acf8268f4463946fc69580df896 --- /dev/null +++ b/policies/reach_target_multi_modal/opus-s2/policy.py @@ -0,0 +1,431 @@ +"""Touch the red sphere with either hand. + +Hand-written control, no learned components: +1. look: the head camera locates the sphere (pinhole model calibrated by moving + the robot around a static sphere; range from the sphere's pixel radius). +2. walk: the base steps to a height-dependent standoff using pelvis odometry. +3. pre/approach: an approximate G1 arm model (URDF geometry, offsets calibrated + against the head camera) with a small damped IK moves the open hand forward + toward the sphere, while the wrist camera steers the sphere to a fixed pixel + (visual servo; corrects the arm model's errors). If the arm runs out of + reach, the body creeps forward a bounded distance. +4. touch: the sphere turns bright red when touched; the hand then holds still + (re-approaching if contact is lost) until the 1 s success condition is met. +""" + +import cv2 +import numpy as np +from scipy.optimize import least_squares + + +# ---------------------------------------------------------------- vision + +def red_mask(im): + r = im.astype(np.int16) + R, G, B = r[..., 0], r[..., 1], r[..., 2] + return (R > 50) & (R > 2 * G + 20) & (R > 2 * B + 20) + + +def bright_red_fraction(im, mask=None): + """Fraction of red pixels that are saturated bright red (the touched colour).""" + if mask is None: + mask = red_mask(im) + n = mask.sum() + if n == 0: + return 0.0, 0 + return float((im[..., 0][mask] > 200).mean()), int(n) + + +def find_sphere(im): + """Return (u, v, r_px, n_pixels, truncated) of the largest red blob, or None.""" + m = red_mask(im).astype(np.uint8) + n, lab, stats, cent = cv2.connectedComponentsWithStats(m, connectivity=8) + if n <= 1: + return None + k = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + area = stats[k, cv2.CC_STAT_AREA] + if area < 4: + return None + x0, y0, w, h = stats[k, 0], stats[k, 1], stats[k, 2], stats[k, 3] + H, W = m.shape + trunc = x0 == 0 or y0 == 0 or x0 + w >= W or y0 + h >= H + if not trunc: + u, v = cent[k] + return float(u), float(v), float(np.sqrt(area / np.pi)), int(area), False + # circle fit to the blob's boundary pixels that are not on the image border + blob = (lab == k).astype(np.uint8) + cnts, _ = cv2.findContours(blob, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) + pts = max(cnts, key=len)[:, 0, :].astype(float) + ok = (pts[:, 0] > 0) & (pts[:, 1] > 0) & (pts[:, 0] < W - 1) & (pts[:, 1] < H - 1) + pts = pts[ok] + if len(pts) < 6: + u, v = cent[k] + return float(u), float(v), float(np.sqrt(area / np.pi)), int(area), True + A = np.c_[2 * pts, np.ones(len(pts))] + b = (pts ** 2).sum(1) + sol, *_ = np.linalg.lstsq(A, b, rcond=None) + cu, cv = sol[0], sol[1] + r = np.sqrt(max(sol[2] + cu ** 2 + cv ** 2, 1.0)) + # contour pixels sit ~0.5 px inside the true edge + return float(cu), float(cv), float(r + 0.5), int(area), True + + +# ---------------------------------------------------------------- kinematics and head camera + +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]) +TOOL = 0.12 # tool point beyond the wrist yaw joint along the hand x axis + + +def arm_chain(side): + """(origin, rotation, axis) per joint in the parent frame. side=+1 left, -1 right.""" + s = side + return [ + (np.array([0.0039563, s * 0.10022, 0.24778]), rpy(s * 0.27931, 0, 0), 1), + (np.array([0, s * 0.038, -0.013831]), rpy(-s * 0.27925, 0, 0), 0), + (np.array([0, s * 0.00624, -0.1032]), np.eye(3), 2), + (np.array([0.015783, 0, -0.080518]), np.eye(3), 1), + (np.array([0.100, s * 0.00188791, -0.010]), np.eye(3), 0), + (np.array([0.038, 0, 0]), np.eye(3), 1), + (np.array([0.046, 0, 0]), np.eye(3), 2), + ] + + +_CHAINS = {1: arm_chain(1), -1: arm_chain(-1)} +_AX = (rx, ry, rz) + + +def fk_points(q, side, tool=TOOL): + """Joint positions and the tool point, pelvis frame (z up from the pelvis).""" + p = TORSO.copy() + R = np.eye(3) + pts = [] + for (o, R0, ax), qi in zip(_CHAINS[side], q): + p = p + R @ o + R = R @ R0 @ _AX[ax](qi) + pts.append(p.copy()) + pts.append(p + R @ np.array([tool, 0, 0])) + return pts, R + + +def fk(q, side, tool=TOOL): + pts, R = fk_points(q, side, tool) + return pts[-1], R + + +# head camera, pelvis frame +CAM_POS = np.array([0.054, 0.0175, 0.474]) +CAM_PITCH = 1.117 +CAM_F = 69.67 +SPHERE_R = 0.0454 + + +def cam_rot(pitch=CAM_PITCH): + """Columns: image-right, image-down, optical axis, in the pelvis frame.""" + z = np.array([np.cos(pitch), 0, -np.sin(pitch)]) + x = np.array([0, -1.0, 0]) + y = np.cross(z, x) + return np.stack([x, y, z], 1) + + +def project(P, pitch=CAM_PITCH, f=CAM_F, cam=CAM_POS): + d = cam_rot(pitch).T @ (np.asarray(P) - cam) + return 42 + f * d[0] / d[2], 42 + f * d[1] / d[2], d[2] + + +def backproject(u, v, r_px, pitch=CAM_PITCH, f=CAM_F, cam=CAM_POS, R=SPHERE_R): + """Sphere centre in the pelvis frame from its pixel centre and pixel radius.""" + ray = np.array([(u - 42) / f, (v - 42) / f, 1.0]) + ray /= np.linalg.norm(ray) + dist = R * np.sqrt(1 + (f / r_px) ** 2) + return cam + cam_rot(pitch) @ (ray * dist) + + +LIM_LO = np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +LIM_HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) + + +def limits(side): + """Joint limits; roll and yaw limits mirror for the right arm.""" + lo, hi = LIM_LO.copy(), LIM_HI.copy() + if side < 0: + for i in (1, 2, 4, 6): + lo[i], hi[i] = -LIM_HI[i], -LIM_LO[i] + return lo, hi + + +UP = np.array([0.0, 0.0, 1.0]) +STARTS = [ + np.array([-1.2, 0.1, 0.0, 0.6, 0.0, 0.0, 0.0]), + np.array([-0.9, 0.2, 0.3, 0.0, 0.0, 0.0, 0.0]), + np.array([-1.5, 0.1, 0.0, 1.0, 0.0, 0.0, 0.0]), + np.array([0.0, 0.1, -0.3, 0.0, 0.0, 0.0, 0.0]), +] +QNOM = np.array([-0.5, 0.15, 0.0, 0.3, 0.0, 0.0, 0.0]) + + +def ik(target, direction, side, q0=None, tool=TOOL, w_dir=0.1, w_nom=0.01, w_smooth=0.0, w_up=0.05, multi=False): + """Joint angles putting the tool point at target with the hand x axis near direction. + + Shoulder adduction and backward pitch are bounded to keep the arm off the torso. + """ + lo, hi = limits(side) + lo = lo + 0.02 + hi = hi - 0.02 + qn = QNOM.copy() + if side > 0: + lo[1] = max(lo[1], -0.05) + else: + qn[[1, 2, 4, 6]] *= -1 + hi[1] = min(hi[1], 0.05) + hi[0] = 0.3 + d = np.asarray(direction, float) + d = d / np.linalg.norm(d) + q0 = qn.copy() if q0 is None else np.asarray(q0, float) + q0 = np.clip(q0, lo, hi) + qp = q0.copy() + + def res(q): + p, R = fk(q, side, tool) + return np.concatenate([p - target, w_dir * (R[:, 0] - d), w_up * (R[:, 2] - UP), w_nom * (q - qn), w_smooth * (q - qp)]) + + starts = [q0] + if multi: + for g in STARTS: + g = g.copy() + if side < 0: + g[[1, 2, 4, 6]] *= -1 + starts.append(np.clip(g, lo, hi)) + best = None + for st in starts: + sol = least_squares(res, st, bounds=(lo, hi)) + if best is None or sol.cost < best.cost: + best = sol + p, R = fk(best.x, side, tool) + return best.x, np.linalg.norm(p - target) + + +# ---------------------------------------------------------------- policy + +ARM_OFS = {1: np.array([0.0, 0.030, 0.019]), -1: np.array([0.0, 0.007, 0.019])} +S0 = -0.12 # approach start, metres behind the sphere centre +S_MAX = 0.25 +CREEP_V = 0.08 +CREEP_MAX = 0.10 # metres the body may creep forward during the reach +SPEED = 0.002 # approach speed, m per step +WU, WV = 41.0, 30.0 # wrist-camera pixel the sphere centre is steered to +WGAIN = 0.12 +WR_MAX = 45.0 # stop steering once the sphere is this close (pixel radius) + + +def _body_to_world(p_body, pose): + x, y, z, yaw = pose + c, s = np.cos(yaw), np.sin(yaw) + return np.array([x + c * p_body[0] - s * p_body[1], y + s * p_body[0] + c * p_body[1], z + p_body[2]]) + + +def _world_to_body(p_w, pose): + x, y, z, yaw = pose + c, s = np.cos(yaw), np.sin(yaw) + dx, dy = p_w[0] - x, p_w[1] - y + return np.array([c * dx + s * dy, -s * dx + c * dy, p_w[2] - z]) + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.t = 0 + self.phase = "look" + self.phase_t = 0 + self.meas = [] + self.q_cmd = {1: np.zeros(7), -1: np.zeros(7)} + self.integ = {1: np.zeros(7), -1: np.zeros(7)} + self.side = 1 + self.Pw = None + self.s = S0 + self.q_ik = None + self.walk_goal = None + self.creep_start = None + self.log = [] + self.ik_err = 0.0 + self.lost = 0 + self.reach_start = None + self.corr = np.zeros(2) # (left, up) correction of the hand target, metres + self.wmeas = None + + # ------------------------------------------------------------------ + def _set_phase(self, name): + self.phase, self.phase_t = name, 0 + + def _pose(self, lo): + return lo[18:22].astype(float) + + def _estimate(self, pose): + u, v, r = np.median(np.array(self.meas), 0) + P = backproject(u, v, r) + self.Pw = _body_to_world(P, pose) + self.meas = [] + + def _solve(self, s, pose): + P = _world_to_body(self.Pw, pose) + sh = fk_points(np.zeros(7), self.side)[0][1] + ARM_OFS[self.side] + d = P - sh + d[2] = 0.0 + d /= np.linalg.norm(d) + perp = np.array([-d[1], d[0], 0.0]) # left of the approach direction + target = P + s * d - ARM_OFS[self.side] + self.corr[0] * perp + np.array([0, 0, self.corr[1]]) + ws = 0.05 if self.q_ik is not None else 0.0 + q, err = ik(target, d, self.side, q0=self.q_ik, w_smooth=ws, multi=self.q_ik is None) + self.q_ik = q + self.ik_err = err + return q + + def _touched(self, tools): + n = 0 + for cam in ("head", "left_wrist", "right_wrist"): + r = tools.image(cam).astype(np.int16) + n += int(((r[..., 0] > 200) & (r[..., 1] < 80) & (r[..., 2] < 80)).sum()) + return n + + def _wrist_servo(self, tools): + cam = "left_wrist" if self.side > 0 else "right_wrist" + d = find_sphere(tools.image(cam)) + self.wmeas = d + if d is None or d[2] > WR_MAX: + return + u, v, r = d[:3] + mpp = SPHERE_R / max(r, 2.0) # metres per pixel at the sphere + eu, ev = (u - WU) * mpp, (v - WV) * mpp + self.corr[0] -= WGAIN * eu # image right = hand's right + self.corr[1] -= WGAIN * ev # image down = down + self.corr = np.clip(self.corr, -0.2, 0.2) + + def _crept(self, pose): + if self.reach_start is None: + self.reach_start = pose.copy() + return np.hypot(pose[0] - self.reach_start[0], pose[1] - self.reach_start[1]) + + def _walk(self, raw, pose, goal): + ex, ey = goal[0] - pose[0], goal[1] - pose[1] + c, s = np.cos(pose[3]), np.sin(pose[3]) + bx, by = c * ex + s * ey, -s * ex + c * ey + if max(abs(bx), abs(by)) < 0.015: + return True + v = np.array([bx, by]) * 2.0 + n = np.linalg.norm(v) + if n > 0.25: + v *= 0.25 / n + if 0 < n < 0.07: + v *= 0.07 / n + raw[0], raw[1] = v + raw[3] = np.clip(2.0 * (goal[2] - pose[3]), -0.5, 0.5) + return False + + # ------------------------------------------------------------------ + def act(self, obs, tools): + lo = obs["low_dim_obs"] + pose = self._pose(lo) + q_meas = {1: lo[0:7].astype(float), -1: lo[9:16].astype(float)} + raw = self.hold.copy() + raw[2] = 0.74 + self.t += 1 + self.phase_t += 1 + + if self.phase in ("look", "relook"): + if self.phase_t >= 5: + d = find_sphere(tools.image("head")) + if d is not None and not (d[4] and d[3] < 60): + self.meas.append(d[:3]) + if self.phase_t >= 12: + if len(self.meas) >= 4: + self._estimate(pose) + P = _world_to_body(self.Pw, pose) + self.side = 1 if P[1] > 0 else -1 + standoff = float(np.clip(0.27 + 0.3 * (P[2] - 0.05), 0.27, 0.34)) + if self.phase == "look" and abs(P[0] - standoff) > 0.02: + g = _body_to_world(np.array([P[0] - standoff, 0.0, 0.0]), pose) + self.walk_goal = (g[0], g[1], pose[3]) + self._set_phase("walk") + else: + self.q_ik = None + self.corr = np.array([0.03 * self.side, 0.02]) + self.q_goal = self._solve(S0, pose) + self.q_start = self.q_cmd[self.side].copy() + self._set_phase("pre") + elif self.phase_t >= 20: + # sphere not (fully) visible: creep forward + self.meas = [] + self.creep_start = pose.copy() + self._set_phase("creep") + elif self.phase == "creep": + raw[0] = 0.12 + d = find_sphere(tools.image("head")) + moved = np.hypot(pose[0] - self.creep_start[0], pose[1] - self.creep_start[1]) + if (d is not None and not d[4]) or moved > 0.15 or self.phase_t > 150: + raw[0] = 0.0 + self._set_phase("settle") + elif self.phase == "settle": + if self.phase_t >= 25: + self._set_phase("relook") + elif self.phase == "walk": + if self._walk(raw, pose, self.walk_goal) or self.phase_t > 200: + raw[0] = raw[1] = raw[3] = 0.0 + self.q_ik = None + self.corr = np.array([0.03 * self.side, 0.02]) + self.q_goal = self._solve(S0, pose) + self.q_start = self.q_cmd[self.side].copy() + self._set_phase("pre") + elif self.phase == "pre": + a = min(1.0, self.phase_t / 40.0) + self.q_cmd[self.side] = self.q_start + a * (self.q_goal - self.q_start) + if self.phase_t >= 55: + self.s = S0 + self._set_phase("approach") + elif self.phase in ("approach", "touch"): + if self._touched(tools) >= 3: + if self.phase == "approach": + self.s += 0.01 + self._set_phase("touch") + self.lost = 0 + elif self.phase == "touch": + self.lost += 1 + if self.lost > 8: + self._set_phase("approach") + if self.phase == "approach": + self._wrist_servo(tools) + close = self.wmeas is not None and self.wmeas[2] > 20 + if self.ik_err < 0.015: + self.s = min(self.s + (SPEED / 2 if close else SPEED), S_MAX) + if (self.ik_err > 0.01 or self.s >= S_MAX) and self._crept(pose) < CREEP_MAX: + raw[0] = CREEP_V # out of reach: bring the body closer + elif self.ik_err > 0.012 and self._crept(pose) < CREEP_MAX: + raw[0] = CREEP_V # holding the touch but the body drifted back + self.q_cmd[self.side] = self._solve(self.s, pose) + + sd = self.side + if self.phase in ("pre", "approach", "touch"): + self.integ[sd] += 0.05 * (self.q_cmd[sd] - q_meas[sd]) + self.integ[sd] = np.clip(self.integ[sd], -0.25, 0.25) + raw[4:11] = self.q_cmd[1] + self.integ[1] + raw[11:18] = self.q_cmd[-1] + self.integ[-1] + raw[18] = raw[19] = 0.0 + self.log.append((self.t, self.phase, round(self.s, 3), round(float(self.ik_err), 3), round(float(raw[0]), 2), np.round(self.corr, 3).tolist(), None if self.wmeas is None else np.round(self.wmeas[:3], 1).tolist())) + return raw diff --git a/policies/reach_target_multi_modal/opus-s3/episodes.csv b/policies/reach_target_multi_modal/opus-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..bde21f220c9fcaf55928945062ef144197f0a534 --- /dev/null +++ b/policies/reach_target_multi_modal/opus-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,279,success,0 +620001,1,282,success,0 +620002,1,287,success,0 +620003,1,292,success,0 +620004,1,290,success,0 +620005,1,287,success,0 +620006,1,282,success,0 +620007,1,279,success,0 +620008,1,263,success,0 +620009,1,289,success,0 +620010,1,266,success,0 +620011,1,282,success,0 +620012,1,295,success,0 +620013,1,267,success,0 +620014,1,276,success,0 +620015,1,284,success,0 +620016,1,266,success,0 +620017,1,266,success,0 +620018,1,280,success,0 +620019,1,279,success,0 +620020,1,292,success,0 +620021,1,288,success,0 +620022,1,288,success,0 +620023,1,257,success,0 +620024,1,280,success,0 +620025,1,267,success,0 +620026,1,265,success,0 +620027,1,301,success,0 +620028,1,293,success,0 +620029,1,299,success,0 +620030,1,282,success,0 +620031,1,255,success,0 +620032,1,286,success,0 +620033,1,282,success,0 +620034,1,289,success,0 +620035,1,280,success,0 +620036,1,273,success,0 +620037,1,280,success,0 +620038,1,278,success,0 +620039,1,282,success,0 +620040,1,293,success,0 +620041,1,291,success,0 +620042,1,293,success,0 +620043,1,281,success,0 +620044,1,276,success,0 +620045,1,291,success,0 +620046,1,288,success,0 +620047,1,264,success,0 +620048,1,263,success,0 +620049,1,283,success,0 +620050,1,282,success,0 +620051,1,262,success,0 +620052,1,294,success,0 +620053,1,271,success,0 +620054,1,264,success,0 +620055,1,294,success,0 +620056,1,287,success,0 +620057,1,290,success,0 +620058,1,272,success,0 +620059,1,290,success,0 +620060,1,288,success,0 +620061,1,290,success,0 +620062,1,289,success,0 +620063,1,279,success,0 +620064,1,283,success,0 +620065,1,285,success,0 +620066,1,296,success,0 +620067,1,287,success,0 +620068,1,284,success,0 +620069,1,275,success,0 +620070,1,282,success,0 +620071,1,287,success,0 +620072,1,294,success,0 +620073,1,292,success,0 +620074,1,282,success,0 +620075,1,284,success,0 +620076,1,275,success,0 +620077,1,281,success,0 +620078,1,280,success,0 +620079,1,288,success,0 +620080,1,292,success,0 +620081,1,276,success,0 +620082,1,290,success,0 +620083,1,271,success,0 +620084,1,260,success,0 +620085,1,284,success,0 +620086,1,266,success,0 +620087,1,279,success,0 +620088,1,275,success,0 +620089,1,264,success,0 +620090,1,280,success,0 +620091,1,268,success,0 +620092,1,287,success,0 +620093,1,291,success,0 +620094,1,289,success,0 +620095,1,295,success,0 +620096,1,264,success,0 +620097,1,290,success,0 +620098,1,290,success,0 +620099,1,279,success,0 diff --git a/policies/reach_target_multi_modal/opus-s3/policy.py b/policies/reach_target_multi_modal/opus-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..54eb34a4d6756668e9a358ee41dcde436a6cf788 --- /dev/null +++ b/policies/reach_target_multi_modal/opus-s3/policy.py @@ -0,0 +1,416 @@ +"""Touch the red sphere with either hand (Unitree G1, scripted). + +Pipeline + 1. Locate the sphere in the head camera: fit a circle (in ray space) to the + red blob boundary -> direction + angular radius -> 3D point, using a + pinhole model of the head camera calibrated from the floor checkerboard. + 2. Store the target in world coordinates (pelvis odometry) and walk the base + so the target sits at a comfortable spot in front of one shoulder. + 3. Re-observe, then reach with an analytic G1 arm model + numerical IK: + sweep the hand forward through the estimate; the sphere lights up while + touched, so the lit stretch of the sweep gives the touch-zone centre + (then z / y sweeps if needed), and the hand holds there. +The arms hang down (out of the head camera view) until the reach starts. +""" + +import cv2 +import numpy as np +from scipy.optimize import least_squares + +# ---------------------------------------------------------------- camera model +F = 72.746 # focal length in px (fovy 60 deg, 84 px) +CX = CY = 41.5 +CAM_PITCH = 1.093 # rad below horizontal +CAM_OFF = np.array([0.07, 0.0, 0.40]) # head camera position in pelvis frame +R_SPHERE = 0.047 # effective sphere radius for the boundary detector + + +def cam_R(th, psi=0.0): + """Camera->frame rotation (camera x right, y down, z forward).""" + z = np.array([np.cos(th) * np.cos(psi), np.cos(th) * np.sin(psi), -np.sin(th)]) + x = np.array([np.sin(psi), -np.cos(psi), 0.0]) + y = np.cross(z, x) + return np.stack([x, y, z], 1) + + +R_CAM = cam_R(CAM_PITCH) + + +def red_mask(im): + im = im.astype(np.int32) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + return (r > 40) & (r > 2 * g + 8) & (r > 2 * b + 8) + + +def bright_count(im): + im = im.astype(np.int32) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + return int(((r > 215) & (g < 110) & (b < 110)).sum()) + + +def fit_sphere(im): + """Fit the red blob. Returns (unit ray in camera frame, angular radius, n boundary pts).""" + m = red_mask(im) + if m.sum() < 4: + return None + n, lab, stats, _ = cv2.connectedComponentsWithStats(m.astype(np.uint8), connectivity=8) + k = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + mk = (lab == k).astype(np.uint8) + cs, _ = cv2.findContours(mk, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) + pts = np.concatenate([c.reshape(-1, 2) for c in cs], 0).astype(float) + h, w = m.shape + keep = (pts[:, 0] > 0) & (pts[:, 0] < w - 1) & (pts[:, 1] > 0) & (pts[:, 1] < h - 1) + pts = pts[keep] + if len(pts) < 6: + return None + ys, xs = np.nonzero(mk) + rays = np.stack([(pts[:, 0] - CX) / F, (pts[:, 1] - CY) / F, np.ones(len(pts))], 1) + rays /= np.linalg.norm(rays, axis=1, keepdims=True) + + def dirf(p): + d = np.array([p[0], p[1], 1.0]) + return d / np.linalg.norm(d) + + x0 = [(xs.mean() - CX) / F, (ys.mean() - CY) / F, np.sqrt(mk.sum() / np.pi) / F] + + def res(p): + return np.arccos(np.clip(rays @ dirf(p[:2]), -1, 1)) - p[2] + + r = least_squares(res, x0) + return dirf(r.x[:2]), r.x[2] + 0.5 / F, len(pts) + + +def locate(im): + """Sphere centre in the pelvis frame (x fwd, y left, z up rel. pelvis).""" + s = fit_sphere(im) + if s is None: + return None + d, alpha, npts = s + if alpha <= 0.01: + return None + D = R_SPHERE / np.sin(alpha) + return R_CAM @ (D * d) + CAM_OFF, npts + + +# ------------------------------------------------------------------ arm model +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]]) + + +TORSO = np.array([-0.0039635, 0, 0.054]) +Q16 = 2 * np.arcsin(0.139201) +TOOL = np.array([0.10, 0.0, 0.0]) + + +def fk(q, side): + """Tool point and wrist rotation (pelvis frame) for arm joints q (7).""" + s = side + R = np.eye(3) + p = TORSO + np.array([0.0039563, s * 0.10022, 0.23778]) + R = rx(s * Q16) @ ry(q[0]) + p = p + R @ np.array([0, s * 0.038, -0.013831]) + R = R @ rx(-s * Q16) @ rx(q[1]) + p = p + R @ np.array([0, s * 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.1, s * 0.00188791, -0.01]) + 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 @ TOOL, R + + +IDX = [0, 1, 2, 3, 5] # joints used by the IK: shoulder pitch/roll/yaw, elbow, wrist pitch + + +# sane working ranges (left arm) for sp, sr, sy, el, wp; roll/yaw mirrored for the right arm +W_LO = np.array([-1.9, 0.0, -0.9, -0.9, -1.0]) +W_HI = np.array([0.5, 0.9, 0.9, 1.6, 1.0]) + + +def limits(side): + lo, hi = W_LO.copy(), W_HI.copy() + if side < 0: + for i in (1, 2): + lo[i], hi[i] = -W_HI[i], -W_LO[i] + return lo, hi + + +def ik(p, side, q0=None, approach=np.array([1.0, 0, 0]), w_ori=0.05): + lo, hi = limits(side) + if q0 is None: + starts = [np.clip(np.array(s, float) * np.array([1, side, side, 1, 1]), lo + 1e-3, hi - 1e-3) + for s in [(-0.3, 0.1, 0, -0.5, 0), (-0.8, 0.1, 0, -0.3, 0), (-0.5, 0.2, 0, 0.3, 0), + (-1.2, 0.1, 0, 0.3, 0), (0, 0, 0, 0, 0)]] + else: + starts = [np.clip(np.asarray(q0)[IDX], lo + 1e-3, hi - 1e-3)] + + def res(x): + q = np.zeros(7) + q[IDX] = x + tip, R = fk(q, side) + return np.r_[(tip - p) * 30, w_ori * (R[:, 0] - approach), 0.003 * x] + + best = None + for s0 in starts: + r = least_squares(res, s0, bounds=(lo, hi)) + if best is None or r.cost < best.cost: + best = r + q = np.zeros(7) + q[IDX] = best.x + return q, float(np.linalg.norm(fk(q, side)[0] - p)) + + +# --------------------------------------------------------------------- policy +def to_world(p_rel, pel): + x, y, z, yaw = pel + c, s = np.cos(yaw), np.sin(yaw) + return np.array([x + c * p_rel[0] - s * p_rel[1], y + s * p_rel[0] + c * p_rel[1], z + p_rel[2]]) + + +def to_rel(p_w, pel): + x, y, z, yaw = pel + c, s = np.cos(yaw), np.sin(yaw) + dx, dy = p_w[0] - x, p_w[1] - y + return np.array([c * dx + s * dy, -s * dx + c * dy, p_w[2] - z]) + + +X_DES = 0.32 # desired target x in pelvis frame before reaching +Y_DES = 0.12 # desired |y| of target (in front of the reaching shoulder) +SX0, SX1 = -0.06, 0.08 # x sweep range (relative to the estimate) +SW = 0.05 # half range of the lateral (z, y) sweeps +S_SPEED = 0.0015 # sweep speed, m per control step +V_MOVE = 0.003 # repositioning speed, m per control step +KI = 0.05 # joint-space integral gain (gravity sag) +# x-sweep lines (dy, dz) tried in turn around the estimate +OFFSETS = [(0, 0), (0, 0.025), (0, -0.025), (0.025, 0), (-0.025, 0), (0.025, 0.025), (-0.025, 0.025), + (0.025, -0.025), (-0.025, -0.025), (0, 0.05), (0, -0.05), (0.05, 0), (-0.05, 0)] +AXES = {"x": 0, "y": 1, "z": 2} +BASE0 = np.array([0.01, 0.0, 0.02]) # systematic offset of the touch zone from the estimate +# arms hang down while observing/walking so the grippers never hide the sphere +CLEAR_L = np.array([0.0, 0.15, 0.0, 1.3, 0.0, 0.0, 0.0]) +CLEAR_R = np.array([0.0, -0.15, 0.0, 1.3, 0.0, 0.0, 0.0]) +T_CLEAR = 30 # steps for the arms to get out of the view +SETTLE = 70 # steps standing still after the walk +SETTLE_OBS = 40 # observe from this step of the settle phase on + + +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 = "observe" + self.t0 = 0 + self.obs_buf = [] + self.target_w = None + self.side = 1 + self.q = np.zeros(7) + self.qi = np.zeros(7) + self.log = [] + self.line = 0 + self.base = np.zeros(3) # centre of the current search (offset from estimate) + self.g = np.zeros(3) # commanded tip offset from the estimate + self.mode = None + self.unlit = 0 + + def pel(self, obs): + return np.asarray(obs["low_dim_obs"][18:22], dtype=np.float64) + + def observe(self, obs, tools): + im = tools.image("head") + r = locate(im) + if r is None: + return None + p, npts = r + return to_world(p, self.pel(obs)), npts + + # ------------------------------------------------------------ search program + def start_xsweep(self): + dy, dz = OFFSETS[self.line % len(OFFSETS)] + c = self.base + np.array([0.0, dy, dz]) + self.go(c + np.array([SX0, 0, 0]), ("sweep", "x", c[0] + SX1)) + + def go(self, p, then): + self.g_to = np.asarray(p, float) + self.mode = "move" + self.after = then + + def begin_sweep(self, axis, end): + self.mode = "sweep" + self.axis = axis + self.end = end + self.end0 = end + self.lit_vals = [] + self.unlit = 0 + + def sweep_done(self): + ax = AXES[self.axis] + if self.lit_vals: + v = np.array(self.lit_vals) + centre = 0.5 * (v.min() + v.max()) + else: + centre = None + self.log.append(("sweep", self.axis, None if centre is None else round(float(centre), 4), + len(self.lit_vals), self.base.round(3).tolist())) + if self.axis == "x": + if centre is None: + self.line += 1 + self.start_xsweep() + return + dy, dz = OFFSETS[self.line % len(OFFSETS)] + self.cur = np.array([centre, self.base[1] + dy, self.base[2] + dz]) + self.go(self.cur, ("hold", "x")) + elif self.axis == "z": + if centre is not None: + self.cur[2] = centre + self.go(self.cur + np.array([0, -SW, 0]), ("sweep", "y", self.cur[1] + SW)) + else: + if centre is not None: + self.cur[1] = centre + self.go(self.cur, ("hold",)) + + def step_search(self, lit, tip_off): + m = self.mode + if m == "move": + d = self.g_to - self.g + n = np.linalg.norm(d) + if n <= V_MOVE: + self.g = self.g_to.copy() + if self.after[0] == "sweep": + self.begin_sweep(self.after[1], self.after[2]) + else: + self.mode = "hold" + self.hold_kind = self.after[1] if len(self.after) > 1 else "final" + self.unlit = 0 + else: + self.g = self.g + d / n * V_MOVE + elif m == "sweep": + ax = AXES[self.axis] + if lit: + self.lit_vals.append(tip_off[ax]) + self.unlit = 0 + else: + self.unlit += 1 + if lit and self.g[ax] >= self.end and self.end < self.end0 + 0.04: + self.end += S_SPEED # still lit at the end of the range: keep going + if (self.lit_vals and self.unlit >= 3) or self.g[ax] >= self.end: + self.sweep_done() + else: + self.g[ax] += S_SPEED + elif m == "hold": + self.unlit = 0 if lit else self.unlit + 1 + if self.hold_kind == "x" and self.unlit > 20: + # x centre alone is not enough: centre z, then y + self.go(self.cur + np.array([0, 0, -SW]), ("sweep", "z", self.cur[2] + SW)) + elif self.unlit > 40: + # lost it: search again around the last centre + self.base = self.cur.copy() + self.line = 0 + self.start_xsweep() + + # ------------------------------------------------------------------- act + def act(self, obs, tools): + t = int(obs["t"]) + a = self.hold.copy() + pel = self.pel(obs) + low = np.asarray(obs["low_dim_obs"], dtype=np.float64) + # both arms hang clear; the reaching arm is overwritten in the reach phase + a[4:11] = CLEAR_L + a[11:18] = CLEAR_R + + if self.phase == "observe": + r = self.observe(obs, tools) if t >= T_CLEAR else None + if r is not None and r[1] >= 20: + self.obs_buf.append(r[0]) + self.log.append(("obs", t, pel.round(3).tolist(), None if r is None else (r[0].round(3).tolist(), r[1]))) + if len(self.obs_buf) >= 8: + self.target_w = np.median(np.array(self.obs_buf), 0) + self.first_w = self.target_w.copy() + rel = to_rel(self.target_w, pel) + self.side = 1 if rel[1] >= 0 else -1 + self.phase = "walk" + self.t0 = t + elif T_CLEAR + 10 < t < T_CLEAR + 160: + a[0] = 0.12 # sphere not well visible: creep forward + return a + + rel = to_rel(self.target_w, pel) + + if self.phase == "walk": + ex = rel[0] - X_DES + ey = rel[1] - self.side * Y_DES + if abs(ex) < 0.02 and abs(ey) < 0.02 or t - self.t0 > 250: + self.phase = "settle" + self.t0 = t + self.obs_buf = [] + self.log.append(("walked", t, pel.round(3).tolist(), rel.round(3).tolist())) + else: + vx = np.clip(1.5 * ex, -0.25, 0.25) + vy = np.clip(1.5 * ey, -0.25, 0.25) + sp = np.hypot(vx, vy) + if sp < 0.07: + k = 0.07 / max(sp, 1e-6) + vx, vy = vx * k, vy * k + a[0], a[1] = vx, vy + return a + + if self.phase == "settle": + if t - self.t0 >= SETTLE_OBS: + r = self.observe(obs, tools) + if r is not None and r[1] >= 20: + self.obs_buf.append(r[0]) + self.log.append(("settle", t, pel.round(3).tolist(), None if r is None else (r[0].round(3).tolist(), r[1]))) + if t - self.t0 >= SETTLE: + if len(self.obs_buf) >= 5: + est = np.median(np.array(self.obs_buf), 0) + if np.linalg.norm(est - self.first_w) < 0.08: + self.target_w = est + self.log.append(("target", t, self.target_w.round(3).tolist(), self.first_w.round(3).tolist())) + self.phase = "reach" + self.t0 = t + self.line = 0 + self.base = BASE0.copy() + dy, dz = OFFSETS[0] + self.g = self.base + np.array([SX0, dy, dz]) + self.start_xsweep() + self.q_from = (CLEAR_L if self.side > 0 else CLEAR_R).copy() + rel = to_rel(self.target_w, pel) + else: + return a + + # ---------------- reach + side = self.side + sl = slice(4, 11) if side > 0 else slice(11, 18) + qm = low[0:7] if side > 0 else low[9:16] + tip_off = fk(qm, side)[0] - rel + lit = bright_count(tools.image("head")) >= 3 + tau = t - self.t0 + if tau >= 40: + self.step_search(lit, tip_off) + q, err = ik(rel + self.g, side, None if tau == 0 else self.q) + self.q = q + if tau < 40: + w = (tau + 1) / 40.0 + cmd = (1 - w) * self.q_from + w * q + else: + self.qi[IDX] = np.clip(self.qi[IDX] + KI * (q - qm)[IDX], -0.15, 0.15) + cmd = q + self.qi + a[sl] = cmd + self.log.append(("reach", t, self.mode, self.line, self.g.round(4).tolist(), tip_off.round(4).tolist(), + rel.round(3).tolist(), round(err, 4), int(lit))) + return a diff --git a/policies/reach_target_single/astra-s1/episodes.csv b/policies/reach_target_single/astra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..d6cd4508ba7182f14ee032f74b1550d8e90fd8d3 --- /dev/null +++ b/policies/reach_target_single/astra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,180,success,0 +620001,1,201,success,0 +620002,1,237,success,0 +620003,1,161,success,0 +620004,1,187,success,0 +620005,1,160,success,0 +620006,1,195,success,0 +620007,1,186,success,0 +620008,1,203,success,0 +620009,1,181,success,0 +620010,1,161,success,0 +620011,1,178,success,0 +620012,1,213,success,0 +620013,1,163,success,0 +620014,1,179,success,0 +620015,1,162,success,0 +620016,1,215,success,0 +620017,1,178,success,0 +620018,1,191,success,0 +620019,1,191,success,0 +620020,1,192,success,0 +620021,1,154,success,0 +620022,1,185,success,0 +620023,1,173,success,0 +620024,1,195,success,0 +620025,1,154,success,0 +620026,1,217,success,0 +620027,1,216,success,0 +620028,1,219,success,0 +620029,1,193,success,0 +620030,1,192,success,0 +620031,1,131,success,0 +620032,1,196,success,0 +620033,1,198,success,0 +620034,1,181,success,0 +620035,1,195,success,0 +620036,1,192,success,0 +620037,1,191,success,0 +620038,1,200,success,0 +620039,1,191,success,0 +620040,1,190,success,0 +620041,1,216,success,0 +620042,1,185,success,0 +620043,1,186,success,0 +620044,1,250,success,0 +620045,1,149,success,0 +620046,1,153,success,0 +620047,1,189,success,0 +620048,1,151,success,0 +620049,1,182,success,0 +620050,1,180,success,0 +620051,1,154,success,0 +620052,1,186,success,0 +620053,1,190,success,0 +620054,1,155,success,0 +620055,1,249,success,0 +620056,1,183,success,0 +620057,1,193,success,0 +620058,1,180,success,0 +620059,1,245,success,0 +620060,1,189,success,0 +620061,1,246,success,0 +620062,1,213,success,0 +620063,1,187,success,0 +620064,1,192,success,0 +620065,1,224,success,0 +620066,0,900,timeout,0 +620067,1,241,success,0 +620068,1,233,success,0 +620069,1,314,success,0 +620070,1,196,success,0 +620071,1,218,success,0 +620072,1,191,success,0 +620073,1,191,success,0 +620074,1,197,success,0 +620075,1,198,success,0 +620076,1,218,success,0 +620077,1,195,success,0 +620078,1,200,success,0 +620079,1,161,success,0 +620080,1,214,success,0 +620081,1,289,success,0 +620082,1,259,success,0 +620083,1,180,success,0 +620084,1,146,success,0 +620085,0,900,timeout,0 +620086,1,155,success,0 +620087,1,184,success,0 +620088,1,222,success,0 +620089,1,199,success,0 +620090,1,163,success,0 +620091,1,282,success,0 +620092,1,226,success,0 +620093,1,249,success,0 +620094,1,217,success,0 +620095,1,214,success,0 +620096,1,212,success,0 +620097,1,214,success,0 +620098,1,184,success,0 +620099,1,186,success,0 diff --git a/policies/reach_target_single/astra-s1/policy.py b/policies/reach_target_single/astra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..dd826d281298f8b767fab01841c1f885fdb0fb18 --- /dev/null +++ b/policies/reach_target_single/astra-s1/policy.py @@ -0,0 +1,93 @@ +"""Deterministic, hand-written visual servo for touching a red target.""" + +import cv2 +import numpy as np + + +def red_blob(image): + """Locate the largest saturated red component in an RGB camera image.""" + r, g, b = (image[:, :, i].astype(float) for i in range(3)) + mask = ((r > 65) & (r > 1.6 * g) & (r > 1.6 * b)).astype(np.uint8) + count, _, stats, centers = cv2.connectedComponentsWithStats(mask) + if count < 2: + return None + component = 1 + np.argmax(stats[1:, 4]) + if stats[component, 4] < 4: + return None + return centers[component], stats[component, 4], mask + + +class Policy: + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=float) + self.a[4:11] = [-0.5, 0, -0.15, 0.5, 0, 0, 0] + # Opening the fingers also clears the wrist camera's view. + self.a[18] = 0 + target = red_blob(tools.image("head")) + if target is not None: + (x, y), _, _ = target + # Coarse aiming only; subsequent motion uses wrist image feedback. + self.a[4] = np.clip(-0.5 + (y - 25) * 0.018, -1.3, -0.1) + self.a[6] = np.clip(-0.15 + (36 - x) * 0.025, -1.0, 0.6) + else: + # High targets can initially lie just above the head camera. + self.a[4] = -0.95 + self.pause = 0 + self.near = False + self.area = 0.0 + self.bright_until = 0 + + def act(self, obs, tools): + t = obs["t"] + if t < 60 or t % 4: + return self.a.copy() + + self.a[0] = 0 + image = tools.image("left_wrist") + target = red_blob(image) + # The target's visible contact highlight is a signal to hold still. + bright = np.count_nonzero( + (image[:, :, 0] > 230) + & (image[:, :, 1] < 35) + & (image[:, :, 2] < 35) + ) + if bright > 200: + if not self.near: + self.near = True + self.pause = t + 80 + self.bright_until = t + 16 + if t < self.bright_until and self.near: + return self.a.copy() + + if target is not None: + (x, y), area, _ = target + self.area = 0.85 * self.area + 0.15 * area + gain = 0.0005 if area > 3500 else 0.0013 + self.a[4] += np.clip((y - 42) * gain, -0.028, 0.028) + self.a[6] += np.clip((42 - x) * gain, -0.028, 0.028) + + # Filter apparent size so a single walking sway does not terminate + # the approach prematurely. Settle before making fine arm motions. + if self.area > 5000 and not self.near: + self.pause = t + 80 + self.near = True + if not self.near and abs(x - 42) < 25 and abs(y - 42) < 25: + self.a[0] = 0.10 + if ( + self.near + and t >= self.pause + and area < 6500 + and abs(x - 42) < 12 + and abs(y - 42) < 12 + ): + self.a[7] += 0.008 + self.a[4] -= 0.0056 + if self.a[7] > 0.85: + self.a[7] = 0.85 + self.a[0] = 0.08 + if self.near and self.a[0] > 0 and area > 5500: + self.a[0] = 0 + self.a[4] = np.clip(self.a[4], -2, 0) + self.a[6] = np.clip(self.a[6], -1.5, 1) + + return self.a.copy() diff --git a/policies/reach_target_single/astra-s2/episodes.csv b/policies/reach_target_single/astra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..4a931c6c94c03f7e1966051396c7ff0165bcc5d8 --- /dev/null +++ b/policies/reach_target_single/astra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,201,success,0 +620001,1,212,success,0 +620002,1,229,success,0 +620003,1,216,success,0 +620004,1,216,success,0 +620005,1,180,success,0 +620006,1,220,success,0 +620007,1,188,success,0 +620008,1,168,success,0 +620009,1,186,success,0 +620010,1,181,success,0 +620011,1,183,success,0 +620012,1,254,success,0 +620013,1,151,success,0 +620014,1,201,success,0 +620015,1,206,success,0 +620016,1,174,success,0 +620017,1,242,success,0 +620018,1,183,success,0 +620019,1,266,success,0 +620020,1,212,success,0 +620021,1,198,success,0 +620022,1,215,success,0 +620023,1,145,success,0 +620024,1,207,success,0 +620025,1,218,success,0 +620026,1,173,success,0 +620027,1,215,success,0 +620028,0,900,timeout,0 +620029,1,213,success,0 +620030,1,217,success,0 +620031,1,142,success,0 +620032,1,210,success,0 +620033,1,203,success,0 +620034,1,185,success,0 +620035,1,203,success,0 +620036,1,211,success,0 +620037,1,243,success,0 +620038,1,213,success,0 +620039,1,212,success,0 +620040,1,209,success,0 +620041,1,250,success,0 +620042,1,228,success,0 +620043,1,185,success,0 +620044,1,189,success,0 +620045,1,219,success,0 +620046,1,206,success,0 +620047,1,210,success,0 +620048,1,151,success,0 +620049,1,192,success,0 +620050,1,186,success,0 +620051,1,155,success,0 +620052,1,246,success,0 +620053,1,208,success,0 +620054,1,157,success,0 +620055,0,900,timeout,0 +620056,1,187,success,0 +620057,1,212,success,0 +620058,1,201,success,0 +620059,1,279,success,0 +620060,1,245,success,0 +620061,1,277,success,0 +620062,1,272,success,0 +620063,1,187,success,0 +620064,1,212,success,0 +620065,1,244,success,0 +620066,1,240,success,0 +620067,1,281,success,0 +620068,1,213,success,0 +620069,1,199,success,0 +620070,1,211,success,0 +620071,1,215,success,0 +620072,1,210,success,0 +620073,1,211,success,0 +620074,1,273,success,0 +620075,1,246,success,0 +620076,1,205,success,0 +620077,1,214,success,0 +620078,1,272,success,0 +620079,1,182,success,0 +620080,1,278,success,0 +620081,1,238,success,0 +620082,1,217,success,0 +620083,1,189,success,0 +620084,1,152,success,0 +620085,1,215,success,0 +620086,1,219,success,0 +620087,1,185,success,0 +620088,1,174,success,0 +620089,1,155,success,0 +620090,1,177,success,0 +620091,1,174,success,0 +620092,1,245,success,0 +620093,1,327,success,0 +620094,1,274,success,0 +620095,0,900,timeout,0 +620096,1,172,success,0 +620097,1,277,success,0 +620098,1,250,success,0 +620099,1,189,success,0 diff --git a/policies/reach_target_single/astra-s2/policy.py b/policies/reach_target_single/astra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..0cd2d7bfa1e5f245893cdef3fc439e9d6fc5f91a --- /dev/null +++ b/policies/reach_target_single/astra-s2/policy.py @@ -0,0 +1,49 @@ +"""Deterministic colour-based visual reach controller.""" +import numpy as np +import cv2 + + +def sphere(im): + a=im.astype(np.int16) + mask=((a[:,:,0]>30)&(a[:,:,0]>a[:,:,1]*2)&(a[:,:,0]>a[:,:,2]*2)).astype(np.uint8) + contours,_=cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) + if not contours:return None + c=max(contours,key=cv2.contourArea) + if cv2.contourArea(c)<3:return None + (x,y),r=cv2.minEnclosingCircle(c) + return np.array([x,y,r]) + +class Policy: + def reset(self,obs,tools): + self.a=np.array(tools.hold_action(),dtype=float) + h=sphere(tools.image('head')) + self.a[4:11]=[0,0,0,0,0,0,0] + if h is not None: + self.a[4]=np.clip(.014*(h[1]-25),-.7,.3) + self.a[6]=np.clip(-.009*(h[0]-12),-.65,.2) + self.contact=-1000 + self.last=None + def act(self,obs,tools): + t=obs['t'] + if t%5:return self.a.copy() + head=tools.image('head'); wrist=tools.image('left_wrist') + bright=((head[:,:,0]>240)&(head[:,:,1]<35)&(head[:,:,2]<35)).sum() + if bright>=4:self.contact=t + self.a[:4]=[0,0,.74,0] + if t-self.contact<80:return self.a.copy() + w=sphere(wrist);h=sphere(head) + self.last=w + if t<25:return self.a.copy() + if w is not None: + self.a[4]+=np.clip(.0008*(w[1]-38),-.025,.025) + self.a[6]-=np.clip(.0008*(w[0]-42),-.025,.025) + if w[2]<45:self.a[0]=.08 + elif w[2]>65:self.a[0]=-.06 + elif h is not None: + # Bring the target into the wrist camera's field of view. + self.a[4]+=.002*(h[1]-(39+65*self.a[4])) + self.a[6]-=.002*(h[0]-(12-60*self.a[6])) + self.a[4]=np.clip(self.a[4],-.9,.9) + self.a[6]=np.clip(self.a[6],-1,.3) + self.a[3]=np.clip(-2*obs['low_dim_obs'][21],-.2,.2) + return self.a.copy() diff --git a/policies/reach_target_single/astra-s3/episodes.csv b/policies/reach_target_single/astra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..ea93c054cc452f0c821ea9fd4c43442904cb4c01 --- /dev/null +++ b/policies/reach_target_single/astra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,338,success,0 +620001,1,349,success,0 +620002,1,397,success,0 +620003,1,344,success,0 +620004,1,313,success,0 +620005,1,344,success,0 +620006,1,337,success,0 +620007,1,338,success,0 +620008,1,333,success,0 +620009,1,398,success,0 +620010,1,318,success,0 +620011,1,338,success,0 +620012,1,338,success,0 +620013,1,473,success,0 +620014,1,337,success,0 +620015,1,338,success,0 +620016,1,338,success,0 +620017,1,318,success,0 +620018,1,771,success,0 +620019,1,337,success,0 +620020,1,338,success,0 +620021,1,318,success,0 +620022,1,313,success,0 +620023,1,805,success,0 +620024,1,343,success,0 +620025,1,765,success,0 +620026,1,821,success,0 +620027,1,497,success,0 +620028,1,314,success,0 +620029,1,318,success,0 +620030,1,367,success,0 +620031,1,811,success,0 +620032,1,404,success,0 +620033,1,344,success,0 +620034,1,338,success,0 +620035,1,338,success,0 +620036,1,339,success,0 +620037,1,767,success,0 +620038,1,348,success,0 +620039,1,338,success,0 +620040,1,353,success,0 +620041,1,373,success,0 +620042,1,318,success,0 +620043,1,408,success,0 +620044,1,343,success,0 +620045,1,328,success,0 +620046,1,318,success,0 +620047,1,313,success,0 +620048,1,811,success,0 +620049,1,338,success,0 +620050,1,338,success,0 +620051,1,550,success,0 +620052,1,811,success,0 +620053,1,388,success,0 +620054,1,389,success,0 +620055,1,337,success,0 +620056,1,343,success,0 +620057,1,353,success,0 +620058,1,333,success,0 +620059,1,387,success,0 +620060,1,358,success,0 +620061,1,353,success,0 +620062,1,333,success,0 +620063,1,403,success,0 +620064,1,337,success,0 +620065,1,333,success,0 +620066,1,397,success,0 +620067,1,358,success,0 +620068,1,358,success,0 +620069,1,343,success,0 +620070,1,792,success,0 +620071,1,772,success,0 +620072,1,333,success,0 +620073,1,338,success,0 +620074,1,349,success,0 +620075,1,396,success,0 +620076,1,403,success,0 +620077,1,800,success,0 +620078,1,342,success,0 +620079,1,318,success,0 +620080,1,354,success,0 +620081,1,526,success,0 +620082,1,333,success,0 +620083,1,333,success,0 +620084,1,344,success,0 +620085,1,403,success,0 +620086,1,407,success,0 +620087,1,408,success,0 +620088,1,811,success,0 +620089,1,816,success,0 +620090,1,817,success,0 +620091,1,756,success,0 +620092,1,354,success,0 +620093,1,368,success,0 +620094,1,333,success,0 +620095,1,314,success,0 +620096,1,339,success,0 +620097,1,354,success,0 +620098,1,401,success,0 +620099,1,788,success,0 diff --git a/policies/reach_target_single/astra-s3/policy.py b/policies/reach_target_single/astra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..e116d3760f8dd07ca1c795449d40a175ee0f7af7 --- /dev/null +++ b/policies/reach_target_single/astra-s3/policy.py @@ -0,0 +1,133 @@ +"""Hand-written, deterministic visual control for touching the left-hand target.""" + +import cv2 +import numpy as np + + +def sphere(im): + """Locate the red silhouette and count its contact-indicator pixels.""" + c = im.astype(np.float32) + mask = ( + (c[:, :, 0] > 70) + & (c[:, :, 0] > 1.8 * c[:, :, 1]) + & (c[:, :, 0] > 1.8 * c[:, :, 2]) + ).astype(np.uint8) + contours, _ = cv2.findContours( + mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE + ) + if not contours: + return None + contour = max(contours, key=cv2.contourArea) + (x, y), radius = cv2.minEnclosingCircle(contour) + bright = int(np.sum((c[:, :, 0] > 230) & (mask > 0))) + return np.array([x, y, radius]), bright + + +class Policy: + def reset(self, obs, tools): + self.a = np.array(tools.hold_action(), dtype=float) + self.height = .74 + self.mode = "walk" + self.feature = None + self.wait = 0 + self.scan = 0 + self.center = np.array([-.7, -.15, -.15, .75, 0, 0, 0]) + + def act(self, obs, tools): + t = obs["t"] + pelvis = obs["low_dim_obs"][18:22] + # Ten-hertz visual feedback; the simulator still receives an action + # on every fifty-hertz control step. + if t % 5: + return self.a.copy() + a = self.a + a[:4] = [0, 0, self.height, 0] + detection = sphere(tools.image("head")) + if detection is None: + if self.mode == "walk": + a[0] = .10 + return a.copy() + wrist = sphere(tools.image("left_wrist")) + if wrist is not None and wrist[1] > 200: + return a.copy() + # The reaching hand can completely hide the sphere. Continue the + # bounded arm search rather than treating occlusion as convergence. + detection = ( + self.feature if self.feature is not None + else np.array([43., 23., 8.8]), + 0, + ) + self.feature = detection[0] + x, y, radius = self.feature + if detection[1] > 30: + return a.copy() + + # Tuned visual-servo gains separate forward, sideways and height errors. + dy = 23 - y + dr = 8.8 - radius + dx = (dy + 4 * dr) / 180 + dh = (dy - 8 * dr) / 300 + lateral = (43 - x) / 150 + + if self.mode == "walk": + # Keep the arm down during approach so it does not hide the target. + a[3] = np.clip(-pelvis[3] * 2, -.15, .15) + if abs(dx) > .014: + a[0] = np.sign(dx) * np.clip(abs(dx) * 1.4, .065, .22) + if abs(lateral) > .012: + a[1] = np.sign(lateral) * np.clip( + abs(lateral) * 1.3, .065, .18 + ) + if a[0] == 0 and a[1] == 0 and t > 50: + self.mode = "height" + self.wait = t + 50 + + elif self.mode == "height": + # Finish stepping and let the base settle before squatting. + if t > self.wait: + self.height = float(np.clip( + self.height + np.clip(dh * .22, -.008, .008), .45, .76 + )) + a[2] = self.height + if t > self.wait + 110: + self.mode = "reach" + self.wait = t + 60 + if self.height > .755: + self.mode = "retreat" + heading = np.array([ + np.cos(pelvis[3]), np.sin(pelvis[3]) + ]) + self.back = pelvis[:2].copy() - .03 * heading + self.height = .74 + self.center[2] = -.15 + (43 - x) * .02 + self.center[3] = .6 if self.mode == "retreat" else .75 + + elif self.mode == "retreat": + # A high target needs clearance for the raised hand. Close this + # short motion against proprioception, not elapsed walking time. + heading = np.array([np.cos(pelvis[3]), np.sin(pelvis[3])]) + error = np.dot(self.back - pelvis[:2], heading) + if error < -.007: + a[0] = -.065 + else: + self.mode = "reach" + self.wait = t + 60 + + elif self.mode == "reach": + a[4:11] += np.clip(self.center - a[4:11], -.07, .07) + if t > self.wait + 60: + self.mode = "scan" + + else: + # Fixed geometric offsets cover residual perspective and tracking + # errors. Contact freezes the current targets for the required hold. + order = [0, -1, 1] + k = self.scan // 15 + target = self.center.copy() + target[2] += order[k % 3] * .20 + target[3] += order[(k // 3) % 3] * .22 + target[0] += order[(k // 9) % 3] * .16 + target[0] = np.clip(target[0], -.78, -.40) + a[4:11] += np.clip(target - a[4:11], -.07, .07) + self.scan += 5 + return a.copy() diff --git a/policies/reach_target_single/deepseek1017-s1/episodes.csv b/policies/reach_target_single/deepseek1017-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..89913099ad1c0f87edb91f56bbcb8e68588660ae --- /dev/null +++ b/policies/reach_target_single/deepseek1017-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,137,success,0 +620001,1,638,success,0 +620002,0,900,timeout,0 +620003,1,414,success,0 +620004,1,126,success,0 +620005,0,900,timeout,0 +620006,1,133,success,0 +620007,1,581,success,0 +620008,1,114,success,0 +620009,0,900,timeout,0 +620010,1,113,success,0 +620011,1,578,success,0 +620012,1,128,success,0 +620013,1,412,success,0 +620014,1,130,success,0 +620015,0,900,timeout,0 +620016,1,282,success,0 +620017,1,118,success,0 +620018,1,475,success,0 +620019,1,135,success,0 +620020,1,124,success,0 +620021,1,570,success,0 +620022,1,116,success,0 +620023,0,900,timeout,0 +620024,1,403,success,0 +620025,1,419,success,0 +620026,0,900,timeout,0 +620027,0,900,timeout,0 +620028,0,900,timeout,0 +620029,0,900,timeout,0 +620030,1,129,success,0 +620031,0,900,timeout,0 +620032,0,900,timeout,0 +620033,1,638,success,0 +620034,0,900,timeout,0 +620035,1,352,success,0 +620036,1,129,success,0 +620037,1,424,success,0 +620038,1,371,success,0 +620039,1,630,success,0 +620040,1,349,success,0 +620041,0,900,timeout,0 +620042,1,128,success,0 +620043,0,900,timeout,0 +620044,1,632,success,0 +620045,0,900,timeout,0 +620046,1,568,success,0 +620047,0,900,timeout,0 +620048,1,412,success,0 +620049,1,499,success,0 +620050,1,364,success,0 +620051,0,900,timeout,0 +620052,0,900,timeout,0 +620053,1,129,success,0 +620054,0,900,timeout,0 +620055,0,900,timeout,0 +620056,0,900,timeout,0 +620057,1,121,success,0 +620058,1,134,success,0 +620059,1,141,success,0 +620060,1,228,success,0 +620061,1,145,success,0 +620062,1,134,success,0 +620063,0,900,timeout,0 +620064,1,136,success,0 +620065,1,684,success,0 +620066,0,900,timeout,0 +620067,1,284,success,0 +620068,1,340,success,0 +620069,0,900,timeout,0 +620070,0,900,timeout,0 +620071,0,900,timeout,0 +620072,1,306,success,0 +620073,1,122,success,0 +620074,1,495,success,0 +620075,0,900,timeout,0 +620076,0,900,timeout,0 +620077,0,900,timeout,0 +620078,1,354,success,0 +620079,1,176,success,0 +620080,1,401,success,0 +620081,0,900,timeout,0 +620082,1,147,success,0 +620083,1,547,success,0 +620084,1,617,success,0 +620085,0,900,timeout,0 +620086,0,900,timeout,0 +620087,0,900,timeout,0 +620088,0,900,timeout,0 +620089,0,900,timeout,0 +620090,0,900,timeout,0 +620091,1,419,success,0 +620092,1,127,success,0 +620093,1,144,success,0 +620094,1,131,success,0 +620095,0,900,timeout,0 +620096,1,179,success,0 +620097,1,140,success,0 +620098,0,900,timeout,0 +620099,0,900,timeout,0 diff --git a/policies/reach_target_single/deepseek1017-s1/policy.py b/policies/reach_target_single/deepseek1017-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..8060e233c7b536136d416088059556d63de7e7e2 --- /dev/null +++ b/policies/reach_target_single/deepseek1017-s1/policy.py @@ -0,0 +1,279 @@ +"""Hand-written visual control policy: walk to the red sphere and touch it +with the left hand. + +The policy only uses the robot's own cameras and proprioception. It + 1. finds the red sphere in the head camera, + 2. drives the base towards it until the sphere is at a comfortable + distance (image row / apparent size), + 3. puts the left arm into a short list of reach poses, holds each one + long enough for the 1 s success test and keeps the pose that brings + the sphere closest in the left wrist camera. +No randomness, no wall clock; every episode follows the same state machine. +""" + +import cv2 +import numpy as np + + +# --------------------------------------------------------------------------- +# small vision helpers +# --------------------------------------------------------------------------- + +def _red_blob(image): + """Return the largest red blob as a dict, or None. + + Args: + image: RGB uint8 image (H, W, 3). + + Returns: + ``{'u','v','area'}`` of the largest red connected component, or None. + """ + if image is None: + return None + r = image[:, :, 0].astype(np.int32) + g = image[:, :, 1].astype(np.int32) + b = image[:, :, 2].astype(np.int32) + mask = ((r > 60) & (r > g * 1.5 + 8) & (r > b * 1.5 + 8)).astype(np.uint8) + n, _lab, stats, cent = cv2.connectedComponentsWithStats(mask, 8) + if n <= 1: + return None + i = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + area = int(stats[i, cv2.CC_STAT_AREA]) + if area < 5: + return None + return {"u": float(cent[i][0]), "v": float(cent[i][1]), "area": area} + + +# --------------------------------------------------------------------------- +# policy +# --------------------------------------------------------------------------- + +class Policy: + """State machine for the reach-target task.""" + + # reach candidates for the left arm: + # [shoulder_pitch, shoulder_roll, shoulder_yaw, elbow, + # wrist_roll, wrist_pitch, wrist_yaw] + CANDIDATES = ( + (0.10, 0.0, -0.65, 0.00, 0.0, 0.00, 0.0), + (0.00, 0.0, -0.65, 0.00, 0.0, 0.00, 0.0), + (0.30, 0.0, -0.65, 0.00, 0.0, 0.00, 0.0), + (-0.10, 0.0, -0.65, 0.00, 0.0, 0.00, 0.0), + (0.10, 0.0, -0.50, 0.00, 0.0, 0.00, 0.0), + (0.10, 0.0, -0.80, 0.00, 0.0, 0.00, 0.0), + (0.00, 0.0, -0.55, 0.00, 0.0, 0.00, 0.0), + (0.00, 0.0, -0.75, 0.00, 0.0, 0.00, 0.0), + (-1.00, 0.0, -0.50, 0.20, 0.5, 1.15, 0.0), + (-1.00, 0.0, -0.50, 0.10, 0.5, 1.25, 0.0), + (-1.00, 0.0, -0.50, 0.00, 0.5, 1.10, 0.0), + (-1.00, 0.0, -0.50, 0.00, 0.5, 1.40, 0.0), + (-0.70, 0.0, -0.50, 0.00, 0.0, 1.10, 0.0), + ) + + # approach parameters + U_TARGET = 47.0 + YAW_GAIN = 0.05 + MAX_APPROACH = 150 + + def reset(self, obs, tools): + """Initialise the per-episode state. + + Args: + obs: First observation. + tools: Camera / hold-action tools. + """ + self.tools = tools + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = "find" + self.phase_step = 0 + self.last = None + self.initial_area = None + self.v_stop = 50.0 + self.area_stop = 260.0 + self.approach_step = 0 + self.settle_step = 0 + self.cand = 0 + self.cand_step = 0 + self.cand_best = -1 + self.best_cand = 0 + self.best_cand_score = -1 + + # -- perception --------------------------------------------------------- + def _see(self): + """Detect the sphere in the head camera; remember the last sighting.""" + blob = _red_blob(self.tools.image("head", 84, 84)) + if blob is not None: + self.last = blob + return blob + + # -- helpers ------------------------------------------------------------ + def _zero_base(self, raw): + """Set zero base velocity and keep the current height.""" + raw[0] = 0.0 + raw[1] = 0.0 + raw[3] = 0.0 + raw[2] = float(self.hold[2]) + return raw + + def _left_arm(self, raw, q): + """Write a left-arm joint target into an action.""" + raw[4:11] = np.asarray(q, dtype=np.float32) + return raw + + # -- main loop ---------------------------------------------------------- + def act(self, obs, tools): + """Return one 20-float physical action. + + Args: + obs: Current observation. + tools: Camera / hold-action tools. + + Returns: + The action to apply for this 20 ms control step. + """ + self.tools = tools + # refresh base/arm state without changing the commanded targets + raw = np.asarray(tools.hold_action(), dtype=np.float32) + self.hold = raw.copy() + + if self.phase == "find": + return self._act_find(raw) + if self.phase == "approach": + return self._act_approach(raw) + if self.phase == "settle": + return self._act_settle(raw) + if self.phase == "reach": + return self._act_reach(raw) + if self.phase == "hold_best": + return self._act_hold_best(raw) + # fallback: hold + return self._zero_base(raw) + + # ------------------------------------------------------------------ + def _act_find(self, raw): + """Turn slowly until the sphere enters the head camera view.""" + blob = self._see() + self.phase_step += 1 + if blob is not None: + self.initial_area = float(blob["area"]) + if self.initial_area >= 125.0: + # already fairly close: stop the base earlier + self.v_stop = 45.0 + self.area_stop = 190.0 + else: + self.v_stop = 50.0 + self.area_stop = 260.0 + self.phase = "approach" + self.phase_step = 0 + elif self.phase_step > 80: + # nothing found after a full sweep; start the reach anyway + self.phase = "reach" + self.phase_step = 0 + self.cand = 0 + self.cand_step = 0 + raw = self._zero_base(raw) + raw[3] = 0.25 + raw[18] = 1.0 + return raw + + # ------------------------------------------------------------------ + def _act_approach(self, raw): + """Drive the base toward the sphere using the head image.""" + blob = self._see() + self.approach_step += 1 + + if blob is not None: + u, v, area = blob["u"], blob["v"], float(blob["area"]) + elif self.last is not None: + u, v, area = self.last["u"], 999.0, 999.0 + else: + u, v, area = self.U_TARGET, 0.0, 0.0 + + wz = float(np.clip(-self.YAW_GAIN * (u - self.U_TARGET), -0.35, 0.35)) + if v < self.v_stop and area < self.area_stop: + vx = 0.25 + elif v < self.v_stop + 5.0 and area < self.area_stop + 30.0: + vx = 0.08 + else: + vx = 0.0 + + raw = self._zero_base(raw) + raw[0] = vx + raw[3] = wz + raw[18] = 1.0 + + done_approach = ( + (blob is not None and (v >= self.v_stop or area >= self.area_stop)) + or vx == 0.0 + or self.approach_step >= self.MAX_APPROACH + or (self.last is not None and area >= 500.0) + ) + if done_approach: + self.phase = "settle" + self.settle_step = 0 + return raw + + # ------------------------------------------------------------------ + def _act_settle(self, raw): + """Let the base controller come to rest before reaching.""" + self._see() + raw = self._zero_base(raw) + raw[18] = 1.0 + self.settle_step += 1 + if self.settle_step >= 8: + self.phase = "reach" + self.phase_step = 0 + self.cand = 0 + self.cand_step = 0 + self.cand_best = -1 + return raw + + # ------------------------------------------------------------------ + def _act_reach(self, raw): + """Hold reach poses and keep the one that gets closest to the sphere.""" + q = self.CANDIDATES[self.cand] + raw = self._zero_base(raw) + raw = self._left_arm(raw, q) + raw[18] = 1.0 # close the left gripper while touching + + wb = _red_blob(self.tools.image("left_wrist", 84, 84)) + area = 0 if wb is None else wb["area"] + if area > self.cand_best: + self.cand_best = area + + self.cand_step += 1 + # If the wrist has not seen the sphere after 22 steps, try the next pose. + if self.cand_step >= 22 and self.cand_best < 180: + self._next_candidate() + # If a candidate is clearly close, give it enough time for the 1 s test. + elif self.cand_step >= 72: + # remember the best candidate + if self.cand_best > self.best_cand_score: + self.best_cand_score = self.cand_best + self.best_cand = self.cand + self._next_candidate() + return raw + + # ------------------------------------------------------------------ + def _next_candidate(self): + """Advance to the next reach candidate, or settle on the best one.""" + if self.cand_best > self.best_cand_score: + self.best_cand_score = self.cand_best + self.best_cand = self.cand + self.cand += 1 + self.cand_step = 0 + self.cand_best = -1 + if self.cand >= len(self.CANDIDATES): + # keep the best pose forever; if it was close the task will have + # succeeded by now, otherwise this is the least-bad option. + self.cand = self.best_cand + self.phase = "hold_best" + + # ------------------------------------------------------------------ + def _act_hold_best(self, raw): + """Keep the best reach pose until the episode ends.""" + q = self.CANDIDATES[self.cand] + raw = self._zero_base(raw) + raw = self._left_arm(raw, q) + raw[18] = 1.0 + return raw diff --git a/policies/reach_target_single/deepseek1017-s2/episodes.csv b/policies/reach_target_single/deepseek1017-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..08e1824b848ac97ad1fbdd155786d266d000cb07 --- /dev/null +++ b/policies/reach_target_single/deepseek1017-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,900,timeout,0 +620001,0,900,timeout,0 +620002,0,900,timeout,0 +620003,0,900,timeout,0 +620004,1,216,success,0 +620005,0,900,timeout,0 +620006,1,225,success,0 +620007,0,900,timeout,0 +620008,0,900,timeout,0 +620009,0,900,timeout,0 +620010,1,482,success,0 +620011,0,900,timeout,0 +620012,0,900,timeout,0 +620013,0,900,timeout,0 +620014,1,225,success,0 +620015,0,900,timeout,0 +620016,0,900,timeout,0 +620017,1,97,success,0 +620018,0,900,timeout,0 +620019,0,900,timeout,0 +620020,1,584,success,0 +620021,0,900,timeout,0 +620022,0,900,timeout,0 +620023,0,900,timeout,0 +620024,0,900,timeout,0 +620025,0,900,timeout,0 +620026,0,900,timeout,0 +620027,0,900,timeout,0 +620028,0,900,timeout,0 +620029,0,900,timeout,0 +620030,0,900,timeout,0 +620031,0,900,timeout,0 +620032,0,900,timeout,0 +620033,0,900,timeout,0 +620034,0,900,timeout,0 +620035,0,900,timeout,0 +620036,1,221,success,0 +620037,0,900,timeout,0 +620038,0,900,timeout,0 +620039,0,900,timeout,0 +620040,0,900,timeout,0 +620041,1,272,success,0 +620042,1,220,success,0 +620043,0,900,timeout,0 +620044,0,900,timeout,0 +620045,0,900,timeout,0 +620046,0,900,timeout,0 +620047,1,246,success,0 +620048,0,900,timeout,0 +620049,0,900,timeout,0 +620050,1,416,success,0 +620051,0,900,timeout,0 +620052,0,900,timeout,0 +620053,1,392,success,0 +620054,0,900,timeout,0 +620055,0,900,timeout,0 +620056,0,900,timeout,0 +620057,1,225,success,0 +620058,1,289,success,0 +620059,1,460,success,0 +620060,0,900,timeout,0 +620061,1,234,success,0 +620062,0,900,timeout,0 +620063,0,900,timeout,0 +620064,0,900,timeout,0 +620065,0,900,timeout,0 +620066,0,900,timeout,0 +620067,0,900,timeout,0 +620068,0,900,timeout,0 +620069,0,900,timeout,0 +620070,0,900,timeout,0 +620071,0,900,timeout,0 +620072,1,415,success,0 +620073,1,279,success,0 +620074,0,900,timeout,0 +620075,0,900,timeout,0 +620076,0,900,timeout,0 +620077,0,900,timeout,0 +620078,0,900,timeout,0 +620079,0,900,timeout,0 +620080,1,133,success,0 +620081,0,900,timeout,0 +620082,1,227,success,0 +620083,1,107,success,0 +620084,0,900,timeout,0 +620085,0,900,timeout,0 +620086,0,900,timeout,0 +620087,0,900,timeout,0 +620088,0,900,timeout,0 +620089,0,900,timeout,0 +620090,0,900,timeout,0 +620091,0,900,timeout,0 +620092,1,566,success,0 +620093,1,278,success,0 +620094,0,900,timeout,0 +620095,0,900,timeout,0 +620096,0,900,timeout,0 +620097,1,229,success,0 +620098,0,900,timeout,0 +620099,0,900,timeout,0 diff --git a/policies/reach_target_single/deepseek1017-s2/policy.py b/policies/reach_target_single/deepseek1017-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..e24e77dc414f1fa40a03a85041843aa71397f25f --- /dev/null +++ b/policies/reach_target_single/deepseek1017-s2/policy.py @@ -0,0 +1,203 @@ +"""Reach the red sphere with the left hand. + +Hand-written visual servoing: + +1. The red target is found in the head camera. The robot walks toward it, + steering so the target stays near the image centre, until its image row + (a proxy for the distance) reaches the value at which the left hand can + reach it. +2. The left arm is moved to a "probe" pose which brings the wrist camera to + the target. +3. A coordinate search over a few arm joints maximises the amount of red + visible in the left wrist camera (i.e. minimises the hand-target + distance). The best pose is held while the base keeps the head-camera + distance constant, until the task succeeds. + +All constants were tuned on the development seeds. +""" + +import cv2 +import numpy as np + + +def _red_blob(im): + """Return (area, cx, cy, x0, x1, y0, y1) of the red blob, or None.""" + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + mask = (((hsv[:, :, 0] < 10) | (hsv[:, :, 0] > 170)) + & (hsv[:, :, 1] > 120) & (hsv[:, :, 2] > 50)) + ys, xs = np.nonzero(mask) + if len(xs) < 4: + return None + return (int(len(xs)), float(xs.mean()), float(ys.mean()), + int(xs.min()), int(xs.max()), int(ys.min()), int(ys.max())) + + +class Policy: + """The control policy that is scored on the hidden seeds.""" + + # [shoulder_pitch, roll, yaw, elbow, wrist_roll, wrist_pitch, wrist_yaw] + ARM_APPROACH = np.array([-0.07, 0.25, -0.80, 0.38, 0.84, -0.59, 0.16]) + ARM_PROBE = np.array([-0.06, 0.25, -0.52, 0.38, 0.86, -0.38, 0.14]) + ARM_FINAL = np.array([-0.06, 0.25, -0.52, 0.28, 0.86, -0.38, 0.02]) + + # (joint index, delta) candidates for the coordinate search, in order + SEARCH_STEPS = ((5, -0.12), (5, -0.24), (5, -0.36), (5, 0.12), + (6, 0.12), (6, -0.12), (6, 0.24), + (3, -0.12), (3, 0.12), (2, 0.12), (2, -0.12), + (0, 0.15), (0, -0.15), (0, 0.30), (0, -0.30)) + SETTLE = 3 + SCORE = 6 + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = 0 + self.cnt = 0 + self.arm = self.ARM_APPROACH.copy() + self.lost = 0 + + # coordinate search bookkeeping + self.round = 0 + self.joint_i = 0 + self.sign_i = 0 + self.stage = 0 # 0 = applying candidate, 1 = scoring it + self.best_arm = self.ARM_PROBE.copy() + self.best_score = -1.0 + self.cand_arm = self.ARM_PROBE.copy() + self.cand_i = -1 + self.scores = [] + + # ------------------------------------------------------------------ # + def _apply_candidate(self): + """Set the arm to the next candidate of the coordinate search.""" + self.cnt = 0 + self.stage = 0 + self.cand_i += 1 + if self.cand_i > len(self.SEARCH_STEPS): + if self.best_score < 100.0: + # no view found the target: creep along and look again + self.phase = 4 + self.cnt = 0 + self.lost = 0 + else: + self.phase = 3 + self.cnt = 0 + self.arm = self.best_arm.copy() + return + if self.cand_i == 0: + self.cand_arm = self.best_arm.copy() + else: + j, d = self.SEARCH_STEPS[self.cand_i - 1] + a = self.best_arm.copy() + a[j] += d + self.cand_arm = a + self.arm = self.cand_arm.copy() + + # ------------------------------------------------------------------ # + def act(self, obs, tools): + head = tools.image('head') + lw = tools.image('left_wrist') + rh = _red_blob(head) + rl = _red_blob(lw) + + raw = self.hold.copy() + vx = 0.0 + wz = 0.0 + + # ---------------- phase 0: walk to the target ---------------- + if self.phase == 0: + if rh is not None: + u, v = rh[1], rh[2] + self.lost = 0 + else: + u, v = 46.0, 99.0 + self.lost += 1 + if rh is not None and v >= 43.5: + self.phase = 1 + self.cnt = 0 + else: + vx = 0.30 if self.lost < 12 else 0.10 + wz = float(np.clip(-0.02 * (u - 46.0), -0.25, 0.25)) + self.arm = self.ARM_APPROACH.copy() + + # ---------------- phase 1: probe pose settles ---------------- + elif self.phase == 1: + self.cnt += 1 + self.arm = self.ARM_PROBE.copy() + if rh is not None: + wz = float(np.clip(-0.02 * (rh[1] - 47.0), -0.2, 0.2)) + if self.cnt >= 8: + self.phase = 2 + self.cnt = 0 + self.best_arm = self.ARM_FINAL.copy() + self.best_score = -1.0 + self.round = 0 + self.joint_i = 0 + self.sign_i = 0 + self.cand_i = -1 + self._apply_candidate() + + # ---------------- phase 2: coordinate search ---------------- + elif self.phase == 2: + self.cnt += 1 + if self.stage == 0: + # let the arm move to the candidate before scoring it + if self.cnt >= 3: + self.stage = 1 + self.scores = [] + if self.stage == 1: + self.scores.append(rl[0] if rl is not None else 0) + if len(self.scores) >= 5: + sc = float(np.median(self.scores)) if self.scores else 0.0 + if self.cand_i == 0: + self.best_score = sc + elif sc > self.best_score * 1.03: + self.best_score = sc + self.best_arm = self.cand_arm.copy() + self._apply_candidate() + + # ---------------- phase 4: creep until the target is seen -------- + elif self.phase == 4: + self.cnt += 1 + if rl is not None and rl[0] > 120: + self.phase = 3 + self.cnt = 0 + self.lost = 0 + elif self.cnt > 150: + self.phase = 3 + self.cnt = 0 + self.lost = 0 + else: + vx = 0.10 if self.cnt <= 80 else -0.10 + + # ---------------- phase 3: hold the contact ---------------- + else: + self.cnt += 1 + if rl is None: + self.lost += 1 + else: + self.lost = 0 + if self.lost > 40: + self.lost = 0 + self.arm[5] = -0.38 if self.arm[5] > -0.2 else -0.20 + + # ---------------- base distance hold ---------------- + if self.phase >= 2 and self.phase != 4: + if rh is not None and rh[2] < 80: + if self.phase == 3: + vx = float(np.clip(0.020 * (47.0 - rh[2]), -0.12, 0.12)) + else: + vx = float(np.clip(0.010 * (47.0 - rh[2]), -0.08, 0.08)) + if abs(vx) < 0.06: + vx = 0.0 + wz = float(np.clip(-0.02 * (rh[1] - 47.0), -0.2, 0.2)) + else: + vx = 0.0 + + if abs(wz) < 0.06: + wz = 0.0 + + raw[0] = vx + raw[1] = 0.0 + raw[3] = wz + raw[4:11] = self.arm + return raw diff --git a/policies/reach_target_single/deepseek1017-s3/episodes.csv b/policies/reach_target_single/deepseek1017-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..c1b00366dfc22afd9f88e678e56ae6ef830fee36 --- /dev/null +++ b/policies/reach_target_single/deepseek1017-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,900,timeout,0 +620001,1,180,success,0 +620002,1,567,success,0 +620003,1,215,success,0 +620004,1,291,success,0 +620005,1,331,success,0 +620006,1,185,success,0 +620007,1,178,success,0 +620008,1,143,success,0 +620009,1,383,success,0 +620010,1,187,success,0 +620011,1,174,success,0 +620012,1,616,success,0 +620013,1,152,success,0 +620014,1,194,success,0 +620015,1,402,success,0 +620016,1,206,success,0 +620017,1,299,success,0 +620018,1,312,success,0 +620019,1,148,success,0 +620020,1,293,success,0 +620021,1,172,success,0 +620022,1,286,success,0 +620023,1,272,success,0 +620024,1,181,success,0 +620025,1,192,success,0 +620026,1,492,success,0 +620027,1,250,success,0 +620028,1,343,success,0 +620029,1,335,success,0 +620030,0,900,timeout,0 +620031,1,297,success,0 +620032,1,367,success,0 +620033,1,179,success,0 +620034,1,174,success,0 +620035,1,236,success,0 +620036,1,261,success,0 +620037,1,186,success,0 +620038,1,163,success,0 +620039,1,179,success,0 +620040,1,198,success,0 +620041,1,185,success,0 +620042,1,258,success,0 +620043,1,332,success,0 +620044,1,179,success,0 +620045,1,163,success,0 +620046,1,293,success,0 +620047,1,294,success,0 +620048,1,639,success,0 +620049,1,230,success,0 +620050,1,227,success,0 +620051,1,315,success,0 +620052,1,366,success,0 +620053,1,267,success,0 +620054,1,628,success,0 +620055,1,350,success,0 +620056,1,786,success,0 +620057,1,189,success,0 +620058,1,218,success,0 +620059,1,323,success,0 +620060,1,174,success,0 +620061,1,338,success,0 +620062,1,327,success,0 +620063,1,752,success,0 +620064,1,334,success,0 +620065,1,252,success,0 +620066,1,638,success,0 +620067,0,900,timeout,0 +620068,1,202,success,0 +620069,1,379,success,0 +620070,1,171,success,0 +620071,1,364,success,0 +620072,1,225,success,0 +620073,1,212,success,0 +620074,1,177,success,0 +620075,1,395,success,0 +620076,1,404,success,0 +620077,1,359,success,0 +620078,1,186,success,0 +620079,1,301,success,0 +620080,1,183,success,0 +620081,1,346,success,0 +620082,1,207,success,0 +620083,1,206,success,0 +620084,1,735,success,0 +620085,1,711,success,0 +620086,1,563,success,0 +620087,1,308,success,0 +620088,1,644,success,0 +620089,0,900,timeout,0 +620090,1,738,success,0 +620091,1,190,success,0 +620092,1,288,success,0 +620093,1,470,success,0 +620094,1,282,success,0 +620095,1,260,success,0 +620096,1,146,success,0 +620097,1,170,success,0 +620098,1,257,success,0 +620099,1,151,success,0 diff --git a/policies/reach_target_single/deepseek1017-s3/policy.py b/policies/reach_target_single/deepseek1017-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..e5b807c31b0f238fb1669d94dc3d1cb14f26d462 --- /dev/null +++ b/policies/reach_target_single/deepseek1017-s3/policy.py @@ -0,0 +1,193 @@ +"""Hand-written control policy for the reach-target task. + +Strategy + 1. Approach: find the red target in the head camera, yaw so it is centred, + walk forward until it is large/close, then stop. + 2. Reach: point the left wrist camera at the target (a small hand-coded pose + search), then servo the wrist with the target's image position and creep + the base forward while the target is centred. When the target fills the + view, hold still for a while (the success condition must persist for 1 s), + then push a little and hold again. + +Only the robot's own cameras and low-dimensional body state are used; all +control logic is hand-written feedback with constants tuned on the development +seeds. No learned model, lookup table or randomness. +""" + +import numpy as np + +# Detection: the target is a red sphere. It can be quite dark when seen from +# the wrist camera, so the thresholds are deliberately loose; the red/other +# channel ratios reject the blue floor and the white/grey robot. +RED_R = 40 +RED_RATIO = 1.35 + +# Left-arm joint targets: [shoulder_pitch, shoulder_roll, shoulder_yaw, elbow, +# wrist_roll, wrist_pitch, wrist_yaw] +# Initial aiming poses, tried in order until the target appears in the wrist +# camera. +Q_SEARCH = [ + [0.0, 0.0, 0.0, 0.0, -0.6, 0.0, -0.7], + [0.0, 0.0, -0.3, 0.0, -0.3, 0.5, -0.3], + [0.0, 0.0, 0.0, 0.0, -0.9, 0.2, -0.7], + [0.0, 0.0, 0.0, 0.0, -0.4, 0.3, -0.9], + [0.0, 0.0, -0.5, 0.0, -0.3, 0.2, -0.6], + [0.3, 0.0, -0.4, 0.3, -0.3, 0.2, -0.5], + [-0.3, 0.0, -0.4, 0.0, -0.3, 0.2, -0.5], +] + + +def red_blob(im): + """Return (u, v, area) of the red target in an RGB image, or None.""" + r = im[..., 0].astype(np.int16) + g = im[..., 1].astype(np.int16) + b = im[..., 2].astype(np.int16) + mask = (r > RED_R) & (r > RED_RATIO * g) & (r > RED_RATIO * b) + n = int(mask.sum()) + if n < 4: + return None + ys, xs = np.nonzero(mask) + return (float(xs.mean()), float(ys.mean()), n) + + +class Policy: + """The control policy scored on hidden seeds.""" + + def reset(self, obs, tools): + """Prepare for one episode (see docs/api.md).""" + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.height = 0.74 + self.raise_t = 0 + self.last_head = None + self.search_t = 0 + self.scan_dir = 1.0 + self._start_reach() + # Initialise the reach state above but begin in the approach phase. + self.phase = "approach" + + def act(self, obs, tools): + """Return the 20-float action for this control step.""" + t = int(obs["t"]) + raw = self.hold.copy() + if self.phase == "approach": + self._approach(t, tools, raw) + else: + self._reach(t, tools, raw) + return raw + + # -- approach --------------------------------------------------------- + def _approach(self, t, tools, raw): + """Walk towards the target seen in the head camera.""" + im = tools.image("head") + s = red_blob(im) + raw[2] = self.height + if s is None: + self.lost += 1 + self.search_t += 1 + if self.last_head is not None and self.last_head[1] > 60: + # Target went below the view: close enough, start reaching. + self._start_reach() + raw[2] = self.height + return + if self.raise_t < 45: + # A target high/far can sit above the head-camera view; + # standing up brings it down into view. + self.raise_t += 1 + self.height = min(0.92, self.height + 0.01) + elif self.lost > 8: + raw[3] = 0.28 * self.scan_dir + if self.lost > 45: + self.scan_dir = -self.scan_dir + self.lost = 0 + if self.search_t > 120: + # Still nothing after a long search: walk forward slowly, + # which also brings high/far targets down into the view. + raw[0] = 0.10 + raw[2] = self.height + return + + self.search_t = 0 + self.lost = 0 + u, v, area = s + self.last_head = (u, v, area) + raw[3] = float(np.clip(-0.010 * (u - 42.0), -0.35, 0.35)) + if v >= 44.0 or area >= 280 or t > 520: + self._start_reach() + raw[2] = self.height + return + raw[0] = 0.18 + raw[2] = self.height + + def _start_reach(self): + """Switch to the visual-servo reach phase.""" + self.phase = "reach" + self.pose_i = 0 + self.q = np.array(Q_SEARCH[0], dtype=float) + self.lost = 0 + self.reach_t = 0 + self.prev_u = 0.0 + self.prev_v = 0.0 + self.last_area = 0.0 + self.hold_t = 0 + self.push_t = 0 + + # -- reach ------------------------------------------------------------ + def _reach(self, t, tools, raw): + """Servo the left wrist camera onto the target and creep into it.""" + self.reach_t += 1 + s = red_blob(tools.image("left_wrist")) + raw[2] = self.height + vx = 0.0 + if s is None: + self.lost += 1 + if self.lost > 12: + # Target out of view: try the next aiming pose. + self.lost = 0 + self.pose_i += 1 + if self.pose_i < len(Q_SEARCH): + self.q = np.array(Q_SEARCH[self.pose_i], dtype=float) + else: + self.q[4] = float(np.clip(self.q[4] - 0.10, -1.2, 0.5)) + self.q[6] = -0.7 + self.pose_i = 0 + else: + self.lost = 0 + u, v, area = s + eu = u - 42.0 + ev = v - 40.0 + du = eu - self.prev_u + dv = ev - self.prev_v + self.prev_u, self.prev_v = eu, ev + # PD control of the two wrist joints that pan/tilt the camera + # towards the target (rates limited, joint limits respected). + dq_wy = -(0.0012 * eu + 0.0007 * du) + dq_wp = 0.0012 * ev + 0.0007 * dv + self.q[6] = float( + np.clip(self.q[6] + np.clip(dq_wy, -0.035, 0.035), -1.15, 0.25) + ) + self.q[5] = float( + np.clip(self.q[5] + np.clip(dq_wp, -0.035, 0.035), -0.55, 1.0) + ) + centered = abs(eu) < 16.0 and abs(ev) < 22.0 + self.last_area = area + if self.hold_t > 0: + # Target fills the view: stand still (success must persist + # for 50 steps) before pushing a little closer. + self.hold_t -= 1 + if self.hold_t == 0: + self.push_t = 45 + elif self.push_t > 0: + self.push_t -= 1 + if centered: + vx = 0.06 + elif centered: + vx = 0.06 + if area > 3800: + self.hold_t = 70 + if area > 6200: + vx = 0.0 + if self.reach_t > 650 and self.hold_t <= 0 and self.push_t <= 0: + # Safety fallback: keep closing in if the servo has not succeeded. + vx = 0.07 + raw[0] = vx + raw[4:11] = self.q diff --git a/policies/reach_target_single/gpt61sol-s1/episodes.csv b/policies/reach_target_single/gpt61sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..3e7c1726c77e8236ad88c3dbdf84757e7b4eb15f --- /dev/null +++ b/policies/reach_target_single/gpt61sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,793,success,0 +620001,0,900,timeout,0 +620002,1,750,success,0 +620003,1,208,success,0 +620004,1,649,success,0 +620005,1,366,success,0 +620006,1,774,success,0 +620007,1,601,success,0 +620008,1,255,success,0 +620009,1,753,success,0 +620010,1,209,success,0 +620011,1,556,success,0 +620012,1,653,success,0 +620013,1,380,success,0 +620014,1,781,success,0 +620015,1,372,success,0 +620016,1,256,success,0 +620017,1,808,success,0 +620018,1,569,success,0 +620019,1,780,success,0 +620020,0,900,timeout,0 +620021,1,319,success,0 +620022,1,812,success,0 +620023,1,344,success,0 +620024,1,761,success,0 +620025,1,258,success,0 +620026,1,462,success,0 +620027,0,900,timeout,0 +620028,1,657,success,0 +620029,1,700,success,0 +620030,1,792,success,0 +620031,1,460,success,0 +620032,0,900,timeout,0 +620033,1,713,success,0 +620034,1,753,success,0 +620035,1,708,success,0 +620036,1,737,success,0 +620037,1,389,success,0 +620038,0,900,timeout,0 +620039,1,808,success,0 +620040,1,706,success,0 +620041,0,900,timeout,0 +620042,1,713,success,0 +620043,1,521,success,0 +620044,1,606,success,0 +620045,1,365,success,0 +620046,1,317,success,0 +620047,1,576,success,0 +620048,1,338,success,0 +620049,1,660,success,0 +620050,1,609,success,0 +620051,1,405,success,0 +620052,1,403,success,0 +620053,1,767,success,0 +620054,1,402,success,0 +620055,1,738,success,0 +620056,1,751,success,0 +620057,0,900,timeout,0 +620058,1,785,success,0 +620059,1,739,success,0 +620060,1,561,success,0 +620061,1,738,success,0 +620062,1,738,success,0 +620063,1,567,success,0 +620064,1,735,success,0 +620065,1,748,success,0 +620066,1,758,success,0 +620067,1,728,success,0 +620068,1,767,success,0 +620069,1,615,success,0 +620070,0,900,timeout,0 +620071,0,900,timeout,0 +620072,0,900,timeout,0 +620073,0,900,timeout,0 +620074,0,900,timeout,0 +620075,1,569,success,0 +620076,1,615,success,0 +620077,1,661,success,0 +620078,1,763,success,0 +620079,1,368,success,0 +620080,0,900,timeout,0 +620081,1,344,success,0 +620082,0,900,timeout,0 +620083,1,560,success,0 +620084,1,376,success,0 +620085,1,771,success,0 +620086,1,431,success,0 +620087,1,605,success,0 +620088,1,346,success,0 +620089,1,432,success,0 +620090,1,441,success,0 +620091,1,289,success,0 +620092,0,900,timeout,0 +620093,1,736,success,0 +620094,1,716,success,0 +620095,1,654,success,0 +620096,1,255,success,0 +620097,0,900,timeout,0 +620098,1,721,success,0 +620099,1,573,success,0 diff --git a/policies/reach_target_single/gpt61sol-s1/policy.py b/policies/reach_target_single/gpt61sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b3bc1c7483177e1afbbf296a96debf6b31ad5cdc --- /dev/null +++ b/policies/reach_target_single/gpt61sol-s1/policy.py @@ -0,0 +1,135 @@ +"""Deterministic image-based left-hand reaching controller.""" +import numpy as np +import cv2 + +def mask_red(im): + # Include the dark side of the sphere, not only its bright highlight. + a=im.astype(np.float32) + return ((a[:,:,0]>20)&(a[:,:,0]>1.7*a[:,:,1])&(a[:,:,0]>1.7*a[:,:,2])).astype(np.uint8) + +def ball(im): + mask=mask_red(im) + n,lab,stats,cent=cv2.connectedComponentsWithStats(mask) + if n<2:return None + k=1+np.argmax(stats[1:,4]) + if stats[k,4]<4:return None + yy,xx=np.where(lab==k) + (x,y),r=cv2.minEnclosingCircle(np.stack([xx,yy],axis=1).astype(np.float32)) + return np.array([x,y]),r +red_ball=ball + +class Policy: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action()).copy() + self.stage='align';self.start=0;self.target=self.a.copy() + self.best=0;self.index=0;self.cycle=0;self.sign=1 + # Live coordinate search: no stored placements or fitted parameters. + self.coords=[(4,.12),(7,.12),(6,.2),(9,.12)] + self.yaw=float(obs['low_dim_obs'][21]) + def score(self,tools): + return int(mask_red(tools.image('left_wrist')).sum()) + def act(self,obs,tools): + t=int(obs['t']);a=self.target.copy();a[:2]=0;a[3]=0 + if self.stage=='align': + b=ball(tools.image('head')) + if b: + (x,y),r=b;ex=45-x + a[1]=np.clip(.008*ex,-.12,.12) if abs(ex)>2 else 0 + if 030) or t>=100: + self.stage='settle';self.start=t;a[:2]=0;a[3]=0 + elif t>=100:self.stage='settle';self.start=t + elif self.stage=='settle': + if t-self.start>=50: + b=ball(tools.image('head')) + y=b[0][1] if b else 22 + # Pinhole height cue distinguishes a high sphere from a low, far one. + self.high_target=bool(b is not None and .30-.05/b[1]*(51.96+.5*(y-42))>.04) + self.target[4:11]=[np.clip(-1-.015*(22-y),-1.65,-.6),0,-.6,1.2,0,0,0] + self.origin=self.a.copy();self.stage='lift';self.start=t + elif self.stage=='lift': + s=min(1,(t-self.start)/40) + a[4]=self.target[4]*s;a[6:11]=0 + if s>=1:self.stage='pose';self.start=t + elif self.stage=='pose': + s=min(1,(t-self.start)/40) + a[4:11]=self.target[4:11];a[6:11]*=s + if t-self.start>=60: + self.best=self.score(tools);self.base=self.target.copy() + self.local_best=self.target.copy();self.local_score=self.best + self.stage='trial';self.start=t;self.sign=1 + if self.best>5000:self.stage='hold';self.start=t + elif self.stage=='trial': + # Compare small positive and negative joint motions in the wrist image. + ix,d=self.coords[self.index] + a=self.base.copy();a[ix]+=self.sign*d + a[4]=np.clip(a[4],-2.0,-.3);a[6]=np.clip(a[6],-1.8,.1) + a[7]=np.clip(a[7],.3,1.9);a[9]=np.clip(a[9],-.7,.7) + if t-self.start>=20: + score=self.score(tools) + if score>self.local_score: + self.local_score=score;self.local_best=a.copy() + if self.sign==1:self.sign=-1;self.start=t + else: + self.target=self.local_best.copy();self.best=self.local_score + self.stage='restore';self.start=t + a=self.target.copy() + elif self.stage=='restore': + if t-self.start>=16: + self.best=self.score(tools) + self.index+=1 + if self.best>5000 or self.index>=len(self.coords): + self.stage='hold';self.start=t + else:self.begin_trial(t) + elif self.stage=='hold': + # Contact must persist for fifty control steps. + if t-self.start>=60: + self.best=self.score(tools) + if self.index=3500 or self.high_target else 'fallback_walk';self.start=t + self.push_origin=obs['low_dim_obs'][18:20].copy() + yaw=float(obs['low_dim_obs'][21]);self.forward=np.array([np.cos(yaw),np.sin(yaw)]) + else: + if self.cycle>=3:self.coords=[(4,.07),(7,.07),(6,.12),(9,.08)] + self.begin_trial(t) + elif self.stage=='fallback_walk': + b=ball(tools.image('head')) + if b: + (x,y),r=b;ex=46-x;ey=41-y + a[0]=np.clip(.008*ey,-.12,.12) if abs(ey)>2 else 0 + a[1]=np.clip(.008*ex,-.10,.10) if abs(ex)>2 else 0 + speed=np.hypot(a[0],a[1]) + if 0=150: + a[:2]=0;self.stage='fallback_settle';self.start=t + elif t-self.start>=150:self.stage='fallback_settle';self.start=t + elif self.stage=='fallback_settle': + if t-self.start>=40: + self.origin=self.target.copy();self.stage='fallback_reach';self.start=t + elif self.stage=='fallback_reach': + s=min(1,(t-self.start)/40) + goal=np.array([-.7,0,-.6,.9,0,0,0]) + a[4:11]=(1-s)*self.origin[4:11]+s*goal + self.target=a.copy() + if t-self.start>=110: + self.best=self.score(tools);self.index=0;self.begin_trial(t) + elif self.stage=='push': + # Close the short approach using measured pelvis displacement. + displacement=np.dot(obs['low_dim_obs'][18:20]-self.push_origin,self.forward) + a[0]=.10 + if displacement>=.05 or t-self.start>65: + a[0]=0;self.stage='push_settle';self.start=t + elif self.stage=='push_settle': + if t-self.start>=60: + self.best=self.score(tools);self.begin_trial(t) + return a + def begin_trial(self,t): + self.base=self.target.copy();self.local_best=self.target.copy() + self.local_score=self.best + self.sign=1;self.stage='trial';self.start=t diff --git a/policies/reach_target_single/gpt61sol-s2/episodes.csv b/policies/reach_target_single/gpt61sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..834609a710483ab613d4b0bb4fd11dbea0bb95bd --- /dev/null +++ b/policies/reach_target_single/gpt61sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,241,success,0 +620001,1,270,success,0 +620002,1,272,success,0 +620003,1,240,success,0 +620004,1,255,success,0 +620005,1,194,success,0 +620006,1,242,success,0 +620007,1,234,success,0 +620008,1,137,success,0 +620009,1,231,success,0 +620010,1,127,success,0 +620011,1,218,success,0 +620012,1,280,success,0 +620013,1,169,success,0 +620014,1,240,success,0 +620015,1,134,success,0 +620016,1,141,success,0 +620017,1,197,success,0 +620018,1,218,success,0 +620019,1,238,success,0 +620020,1,251,success,0 +620021,1,123,success,0 +620022,1,222,success,0 +620023,1,135,success,0 +620024,1,237,success,0 +620025,1,161,success,0 +620026,1,200,success,0 +620027,1,296,success,0 +620028,0,900,timeout,0 +620029,1,266,success,0 +620030,1,241,success,0 +620031,1,134,success,0 +620032,1,267,success,0 +620033,1,266,success,0 +620034,1,220,success,0 +620035,1,237,success,0 +620036,1,238,success,0 +620037,1,186,success,0 +620038,1,240,success,0 +620039,1,253,success,0 +620040,1,234,success,0 +620041,1,268,success,0 +620042,1,232,success,0 +620043,1,286,success,0 +620044,1,236,success,0 +620045,0,900,timeout,0 +620046,1,120,success,0 +620047,1,237,success,0 +620048,1,216,success,0 +620049,1,217,success,0 +620050,1,207,success,0 +620051,1,238,success,0 +620052,1,411,success,0 +620053,1,218,success,0 +620054,1,238,success,0 +620055,0,900,timeout,0 +620056,1,290,success,0 +620057,1,234,success,0 +620058,1,235,success,0 +620059,1,317,success,0 +620060,1,348,success,0 +620061,1,318,success,0 +620062,1,313,success,0 +620063,1,219,success,0 +620064,1,238,success,0 +620065,1,303,success,0 +620066,1,255,success,0 +620067,1,305,success,0 +620068,1,260,success,0 +620069,1,237,success,0 +620070,1,315,success,0 +620071,1,310,success,0 +620072,1,234,success,0 +620073,1,234,success,0 +620074,1,281,success,0 +620075,1,255,success,0 +620076,1,249,success,0 +620077,1,256,success,0 +620078,1,271,success,0 +620079,1,126,success,0 +620080,1,248,success,0 +620081,1,130,success,0 +620082,1,252,success,0 +620083,1,217,success,0 +620084,1,144,success,0 +620085,1,334,success,0 +620086,1,155,success,0 +620087,1,234,success,0 +620088,1,123,success,0 +620089,1,152,success,0 +620090,1,299,success,0 +620091,1,75,success,0 +620092,1,289,success,0 +620093,1,319,success,0 +620094,1,312,success,0 +620095,1,319,success,0 +620096,1,138,success,0 +620097,1,317,success,0 +620098,1,220,success,0 +620099,1,232,success,0 diff --git a/policies/reach_target_single/gpt61sol-s2/policy.py b/policies/reach_target_single/gpt61sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b5757c3a3d339418d384f586ea5226535188c79b --- /dev/null +++ b/policies/reach_target_single/gpt61sol-s2/policy.py @@ -0,0 +1,68 @@ +"""Deterministic color-based visual controller for a left-hand reach.""" +import numpy as np + + +def target(image): + a = image.astype(np.float32) + r, g, b = a[:, :, 0], a[:, :, 1], a[:, :, 2] + mask = (r > 20) & (r > 1.5*g) & (r > 1.5*b) + y, x = np.nonzero(mask) + if len(x) < 5: + return None + return float(x.mean()), float(y.mean()), len(x), int(np.sum(mask & (r > 220))) + + +class Policy: + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=np.float32) + self.a[4:11] = [-1.1, 0, -1, 1.2, 0, 0, 0] + self.a[18] = 0 + h = target(tools.image('head')) + self.initial_target = h + self.high = bool(h and h[1] < 10) + if h and h[1] < 10: + self.a[4] = -1.55+.02*h[1] + self.a[6] = np.clip(-.5-.025*(h[0]-25),-1.5,0) + self.a[7] = 1.8-.025*h[1] + self.frozen = False + self.freeze_t = 0 + self.missing = 0 + + def act(self, obs, tools): + t = int(obs['t']) + if t >= 60 and t % 5 == 0: + m = target(tools.image('left_wrist')) + if m and m[3] > 100: + if not self.frozen: + self.freeze_t = t + self.frozen = True + self.a[:2] = 0 + if self.frozen: + if t-self.freeze_t > 85 and (m is None or m[3] < 20): + self.frozen = False + else: + return self.a.copy() + if m is None: + self.missing += 1 + if self.missing == 10 and not self.high and self.initial_target and self.initial_target[1] < 16: + h = self.initial_target + self.a[4] = -1.55+.02*h[1] + self.a[6] = np.clip(-.5-.025*(h[0]-25),-1.5,0) + self.a[7] = 1.8-.025*h[1] + self.a[9:11] = [0, 0] + self.high = True + if self.missing == 2: + self.a[9:11] = [-.5, -.4] + elif self.missing > 10 and self.missing % 8 == 0: + scan = [(-.8,-.4), (-.5,0), (-.8,0), (-.5,.4), (.4,-.4), (0,0)] + self.a[9:11] = scan[(self.missing//8-2) % len(scan)] + else: + self.missing = 0 + if m: + x,y,n,bright = m + self.a[9] += np.clip((y-42)*.003, -.04, .04) + self.a[10] -= np.clip((x-42)*.003, -.04, .04) + self.a[9:11] = np.clip(self.a[9:11], -1.4, 1.4) + if t > 120: + self.a[0] = .08 + return self.a.copy() diff --git a/policies/reach_target_single/gpt61sol-s3/episodes.csv b/policies/reach_target_single/gpt61sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..a6925aec95292ba062a61440dd7a15736173a5c1 --- /dev/null +++ b/policies/reach_target_single/gpt61sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,271,success,0 +620001,1,190,success,0 +620002,1,184,success,0 +620003,1,187,success,0 +620004,1,183,success,0 +620005,1,169,success,0 +620006,1,199,success,0 +620007,1,361,success,0 +620008,1,221,success,0 +620009,1,187,success,0 +620010,1,226,success,0 +620011,1,184,success,0 +620012,1,178,success,0 +620013,1,205,success,0 +620014,1,154,success,0 +620015,1,169,success,0 +620016,1,221,success,0 +620017,1,162,success,0 +620018,1,190,success,0 +620019,1,152,success,0 +620020,1,250,success,0 +620021,1,166,success,0 +620022,1,222,success,0 +620023,1,180,success,0 +620024,1,263,success,0 +620025,1,169,success,0 +620026,1,208,success,0 +620027,1,199,success,0 +620028,0,900,timeout,0 +620029,1,158,success,0 +620030,1,190,success,0 +620031,1,176,success,0 +620032,1,193,success,0 +620033,1,361,success,0 +620034,1,184,success,0 +620035,1,230,success,0 +620036,1,262,success,0 +620037,1,193,success,0 +620038,1,290,success,0 +620039,1,435,success,0 +620040,1,401,success,0 +620041,1,247,success,0 +620042,1,195,success,0 +620043,1,206,success,0 +620044,1,203,success,0 +620045,1,166,success,0 +620046,1,166,success,0 +620047,1,171,success,0 +620048,1,169,success,0 +620049,1,245,success,0 +620050,1,277,success,0 +620051,1,182,success,0 +620052,1,206,success,0 +620053,1,182,success,0 +620054,1,179,success,0 +620055,0,900,timeout,0 +620056,1,187,success,0 +620057,1,222,success,0 +620058,1,169,success,0 +620059,1,264,success,0 +620060,1,240,success,0 +620061,1,219,success,0 +620062,1,261,success,0 +620063,1,194,success,0 +620064,1,267,success,0 +620065,1,255,success,0 +620066,1,193,success,0 +620067,1,195,success,0 +620068,1,424,success,0 +620069,1,197,success,0 +620070,1,190,success,0 +620071,1,187,success,0 +620072,1,226,success,0 +620073,1,241,success,0 +620074,1,184,success,0 +620075,1,190,success,0 +620076,1,205,success,0 +620077,1,184,success,0 +620078,1,361,success,0 +620079,1,227,success,0 +620080,1,236,success,0 +620081,1,199,success,0 +620082,1,241,success,0 +620083,1,229,success,0 +620084,1,331,success,0 +620085,1,205,success,0 +620086,1,182,success,0 +620087,1,206,success,0 +620088,1,206,success,0 +620089,1,206,success,0 +620090,1,191,success,0 +620091,1,175,success,0 +620092,1,232,success,0 +620093,1,267,success,0 +620094,1,255,success,0 +620095,0,900,timeout,0 +620096,1,222,success,0 +620097,1,233,success,0 +620098,1,190,success,0 +620099,1,199,success,0 diff --git a/policies/reach_target_single/gpt61sol-s3/policy.py b/policies/reach_target_single/gpt61sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..9a3357ebadffcd31b3c86d511848ef0a348f2408 --- /dev/null +++ b/policies/reach_target_single/gpt61sol-s3/policy.py @@ -0,0 +1,115 @@ +"""Deterministic visual reaching controller. + +The head camera guides a short approach. A geometric, hand-tuned arm search +handles depth variation; the wrist camera makes local aiming corrections. +The sphere's contact colour stops the arm at its measured configuration. +""" + +import cv2 +import numpy as np + + +def sphere(im): + """Segment the red target and count its bright contact pixels.""" + a=im.astype(np.int16) + mask=((a[:,:,0]>65)&(a[:,:,0]>2*a[:,:,1]+20)&(a[:,:,0]>2*a[:,:,2]+20)).astype(np.uint8) + n,lab,stat,cen=cv2.connectedComponentsWithStats(mask,8) + if n<2:return None + i=1+np.argmax(stat[1:,4]);m=lab==i + x,y,w,h,area=stat[i] + return np.array([x+(w-1)*.5,y+(h-1)*.5]),int(area),int(np.sum(im[:,:,0][m]>220)) + + +class Policy: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action(),dtype=np.float32) + self.a[4:11]=[-.5,0,-.5,.8,0,0,0] + self.yaw=float(obs['low_dim_obs'][21]);self.phase=0 + self.move=np.zeros(2);self.ref=None;self.pose=np.array([-.5,-.5,.8]) + self.search=0;self.age=0;self.touch=False;self.lost=0;self.grid=None + self.corr=np.zeros(2);self.area=150;self.servo_age=0;self.servo_lost=0 + + def make_grid(self,u,v,area): + # Apparent size selects the starting elbow bend; nearby poses are + # generated analytically, with no seed-specific stored trajectories. + ec=float(np.clip(.8-.006*(area-150),-.75,1.6)) + yc=-.5-.017*(u-44) + grid=[] + for de in [0,-.3,.3,-.6,.6]: + e=np.clip(ec+de,-.9,1.8) + pc=-.5-.75*(e-.8)+.008*(v-37) + for dp,dy in [(0,0),(0,-.12),(0,.12),(-.12,0),(.12,0),(-.12,-.12),(-.12,.12),(.12,-.12),(.12,.12)]: + grid.append(np.array([np.clip(pc+dp,-.98,.8),np.clip(yc+dy,-1.2,.2),e])) + return grid + + def freeze_contact(self,q): + # Stop at the measured pose, including small gravity compensation, + # so an unfinished position command cannot sweep past the target. + self.a[4:11]=q[:7] + self.a[4]-=.025 + self.a[7]-=.025 + self.a[9]-=.03 + self.pose=self.a[[4,6,7]].copy() + self.corr[:]=0 + self.touch=True + self.lost=0 + + def act(self,obs,tools): + t=obs['t'];q=obs['low_dim_obs'] + if self.phase==1 and t%3!=0 and not self.touch: + quick=sphere(tools.image('head')) + if quick is not None and quick[2]>12: + self.freeze_contact(q) + self.ref=quick[0].copy() + if t%3==0: + s=sphere(tools.image('head')) + bright=0 + if s is not None:uv,area,bright=s + # Walk before reaching, then stand for the arm search. + if self.phase==0: + if s is not None: + u,v=uv;ex=44-u;ey=37-v + vx=float(np.clip(.01*ey,-.12,.2));vy=float(np.clip(.006*ex,-.15,.15)) + if abs(ey)<3:vx=0 + elif abs(vx)<.06:vx=np.sign(vx)*.06 + if abs(ex)<4:vy=0 + elif abs(vy)<.06:vy=np.sign(vy)*.06 + self.move[:]=[vx,vy] + if ((abs(ey)<4 and abs(ex)<5 and t>45) or t>=180 or bright>12): + self.phase=1;self.move[:]=0;self.start=t;self.ref=uv.copy();self.area=area + else:self.move[:]=0 + if self.phase==1: + if self.grid is None and t>=self.start+24: + if s is not None and area>.7*self.area:self.ref=uv.copy();self.area=area + self.grid=self.make_grid(*self.ref,self.area) + if bright>12: + if not self.touch: + self.freeze_contact(q) + if s is not None:self.ref=uv.copy() + self.touch=True;self.lost=0 + elif self.touch: + self.lost+=3 + if self.lost>18:self.touch=False;self.age=18 + if self.grid is not None and not self.touch: + wrist=sphere(tools.image('left_wrist')) + if wrist is not None and wrist[1]>200 and self.servo_age<60: + self.servo_age+=3 + wu,wv=wrist[0] + self.a[4]=np.clip(self.a[4]+np.clip(.0025*(wv-42),-.035,.035),-.98,.85) + self.a[6]=np.clip(self.a[6]-np.clip(.0025*(wu-42),-.035,.035),-1.3,.3) + self.pose=self.a[[4,6,7]].copy() + self.age=0 + a=self.a.copy();a[:2]=self.move + a[3]=np.clip(-3*(float(q[21])-self.yaw),-.3,.3) + return a + self.age+=3 + if self.age>=18: + self.age=0;self.servo_age=0;self.pose=self.grid[self.search].copy();self.search=(self.search+1)%len(self.grid) + if s is not None and area>.7*self.area: + self.corr=np.clip(uv-self.ref,-6,6) + self.a[4]=np.clip(self.pose[0]+.008*self.corr[1],-.98,.85) + self.a[6]=np.clip(self.pose[1]-.012*self.corr[0],-1.3,.3) + self.a[7]=self.pose[2] + a=self.a.copy();a[:2]=self.move + a[3]=np.clip(-3*(float(q[21])-self.yaw),-.3,.3) + return a diff --git a/policies/reach_target_single/gpt61terra-s1/episodes.csv b/policies/reach_target_single/gpt61terra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..e66a570f4447ed19df1a4dab5c036600d8340b44 --- /dev/null +++ b/policies/reach_target_single/gpt61terra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,900,timeout,0 +620001,1,381,success,0 +620002,0,900,timeout,0 +620003,0,900,timeout,0 +620004,0,900,timeout,0 +620005,1,446,success,0 +620006,1,270,success,0 +620007,1,367,success,0 +620008,0,900,timeout,0 +620009,0,900,timeout,0 +620010,0,900,timeout,0 +620011,1,405,success,0 +620012,1,279,success,0 +620013,0,900,timeout,0 +620014,0,900,timeout,0 +620015,0,900,timeout,0 +620016,0,900,timeout,0 +620017,1,256,success,0 +620018,0,900,timeout,0 +620019,0,900,timeout,0 +620020,0,900,timeout,0 +620021,1,70,success,0 +620022,0,900,timeout,0 +620023,0,900,timeout,0 +620024,1,372,success,0 +620025,0,900,timeout,0 +620026,0,900,timeout,0 +620027,0,900,timeout,0 +620028,0,900,timeout,0 +620029,1,251,success,0 +620030,1,266,success,0 +620031,0,900,timeout,0 +620032,0,900,timeout,0 +620033,0,900,timeout,0 +620034,1,389,success,0 +620035,1,367,success,0 +620036,1,267,success,0 +620037,0,900,timeout,0 +620038,0,900,timeout,0 +620039,1,420,success,0 +620040,0,900,timeout,0 +620041,0,900,timeout,0 +620042,0,900,timeout,0 +620043,0,900,timeout,0 +620044,0,900,timeout,0 +620045,1,69,success,0 +620046,1,70,success,0 +620047,1,249,success,0 +620048,1,80,success,0 +620049,1,364,success,0 +620050,0,900,timeout,0 +620051,0,900,timeout,0 +620052,0,900,timeout,0 +620053,0,900,timeout,0 +620054,0,900,timeout,0 +620055,0,900,timeout,0 +620056,0,900,timeout,0 +620057,0,900,timeout,0 +620058,0,900,timeout,0 +620059,1,286,success,0 +620060,1,444,success,0 +620061,0,900,timeout,0 +620062,0,900,timeout,0 +620063,0,900,timeout,0 +620064,0,900,timeout,0 +620065,1,289,success,0 +620066,0,900,timeout,0 +620067,1,293,success,0 +620068,1,414,success,0 +620069,0,900,timeout,0 +620070,0,900,timeout,0 +620071,0,900,timeout,0 +620072,0,900,timeout,0 +620073,0,900,timeout,0 +620074,1,371,success,0 +620075,0,900,timeout,0 +620076,0,900,timeout,0 +620077,0,900,timeout,0 +620078,1,367,success,0 +620079,1,369,success,0 +620080,1,364,success,0 +620081,0,900,timeout,0 +620082,0,900,timeout,0 +620083,0,900,timeout,0 +620084,0,900,timeout,0 +620085,0,900,timeout,0 +620086,0,900,timeout,0 +620087,0,900,timeout,0 +620088,0,900,timeout,0 +620089,0,900,timeout,0 +620090,0,900,timeout,0 +620091,0,900,timeout,0 +620092,0,900,timeout,0 +620093,1,285,success,0 +620094,0,900,timeout,0 +620095,0,900,timeout,0 +620096,0,900,timeout,0 +620097,0,900,timeout,0 +620098,0,900,timeout,0 +620099,0,900,timeout,0 diff --git a/policies/reach_target_single/gpt61terra-s1/policy.py b/policies/reach_target_single/gpt61terra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..5c037d5f5a4355968dccdebf97158de4f80cd3b1 --- /dev/null +++ b/policies/reach_target_single/gpt61terra-s1/policy.py @@ -0,0 +1,29 @@ +import numpy as np +import cv2 +class Policy: + def reset(self,obs,tools): + self.hold=np.array(tools.hold_action(),dtype=np.float32); self.phase=0; self.stable=0; self.last=None; self.pre=0 + def act(self,obs,tools): + a=self.hold.copy(); t=obs['t']; yaw=obs['low_dim_obs'][21] + if t<80: + a[4:8]=[-1,0,-.5,1] + return a + if self.phase==0: + if t%3==0 or self.last is None: + im=tools.image('head'); r=im[:,:,0].astype(np.int16); g=im[:,:,1].astype(np.int16); b=im[:,:,2].astype(np.int16) + mask=((r>65)&(r>g*1.5)&(r>b*1.5)).astype(np.uint8); n,lab,stats,cent=cv2.connectedComponentsWithStats(mask) + if n>1: + k=1+np.argmax(stats[1:,4]); self.last=cent[k] if stats[k,4]>=5 else None + if self.last is not None: + x,y=self.last; ex=x-38; ey=37-y + if abs(ex)<4 and abs(ey)<4: self.stable+=1 + else: self.stable=0 + if self.stable>=12 or t>250: self.phase=1; self.start=t + else: + if abs(ey)>3: a[0]=np.sign(ey)*np.clip(abs(ey)*.012,.08,.22) + if abs(ex)>3: a[1]=-np.sign(ex)*np.clip(abs(ex)*.01,.08,.17) + a[3]=np.clip(-2*yaw,-.25,.25) + if self.phase==1: + poses=[(-.5,-.5,.8),(-.8,-.5,1.2),(0,-.5,0),(-.8,0,1.2),(-.5,0,.8),(-.5,-.5,1.2),(-.8,-.5,.8),(-.2,-.5,.8),(-.2,0,1.2),(-1.1,-.5,1.2),(-.5,0,1.5),(-.8,0,.8)] + i=min((t-self.start)//65,len(poses)-1); p,y,e=poses[i]; a[4:8]=[p,0,y,e] + return a diff --git a/policies/reach_target_single/gpt61terra-s2/episodes.csv b/policies/reach_target_single/gpt61terra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..264e4bd6bf2ea1a02b14e22aab2381cc0be13030 --- /dev/null +++ b/policies/reach_target_single/gpt61terra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,361,success,0 +620001,1,247,success,0 +620002,1,168,success,0 +620003,1,160,success,0 +620004,1,350,success,0 +620005,1,186,success,0 +620006,1,177,success,0 +620007,0,900,timeout,0 +620008,1,682,success,0 +620009,1,166,success,0 +620010,1,203,success,0 +620011,0,900,timeout,0 +620012,1,161,success,0 +620013,1,712,success,0 +620014,1,359,success,0 +620015,1,166,success,0 +620016,0,900,timeout,0 +620017,1,152,success,0 +620018,1,160,success,0 +620019,1,359,success,0 +620020,0,900,timeout,0 +620021,1,163,success,0 +620022,1,241,success,0 +620023,1,170,success,0 +620024,1,360,success,0 +620025,1,773,success,0 +620026,0,900,timeout,0 +620027,0,900,timeout,0 +620028,1,434,success,0 +620029,1,153,success,0 +620030,1,178,success,0 +620031,0,900,timeout,0 +620032,1,522,success,0 +620033,1,714,success,0 +620034,0,900,timeout,0 +620035,0,900,timeout,0 +620036,1,160,success,0 +620037,1,159,success,0 +620038,1,364,success,0 +620039,0,900,timeout,0 +620040,0,900,timeout,0 +620041,1,200,success,0 +620042,0,900,timeout,0 +620043,0,900,timeout,0 +620044,0,900,timeout,0 +620045,1,132,success,0 +620046,1,162,success,0 +620047,1,148,success,0 +620048,1,160,success,0 +620049,0,900,timeout,0 +620050,0,900,timeout,0 +620051,0,900,timeout,0 +620052,0,900,timeout,0 +620053,1,162,success,0 +620054,1,716,success,0 +620055,1,176,success,0 +620056,1,166,success,0 +620057,0,900,timeout,0 +620058,1,360,success,0 +620059,1,182,success,0 +620060,1,236,success,0 +620061,1,183,success,0 +620062,0,900,timeout,0 +620063,1,518,success,0 +620064,1,358,success,0 +620065,1,157,success,0 +620066,1,532,success,0 +620067,1,176,success,0 +620068,0,900,timeout,0 +620069,1,714,success,0 +620070,0,900,timeout,0 +620071,1,230,success,0 +620072,0,900,timeout,0 +620073,0,900,timeout,0 +620074,0,900,timeout,0 +620075,1,531,success,0 +620076,0,900,timeout,0 +620077,1,187,success,0 +620078,1,816,success,0 +620079,1,164,success,0 +620080,1,364,success,0 +620081,1,516,success,0 +620082,0,900,timeout,0 +620083,0,900,timeout,0 +620084,1,680,success,0 +620085,0,900,timeout,0 +620086,1,720,success,0 +620087,0,900,timeout,0 +620088,0,900,timeout,0 +620089,0,900,timeout,0 +620090,1,161,success,0 +620091,1,158,success,0 +620092,1,368,success,0 +620093,1,183,success,0 +620094,0,900,timeout,0 +620095,1,157,success,0 +620096,1,779,success,0 +620097,0,900,timeout,0 +620098,1,252,success,0 +620099,1,709,success,0 diff --git a/policies/reach_target_single/gpt61terra-s2/policy.py b/policies/reach_target_single/gpt61terra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b38f686783a9ec80d5ecfe2961804ef32621a05d --- /dev/null +++ b/policies/reach_target_single/gpt61terra-s2/policy.py @@ -0,0 +1,34 @@ +import numpy as np +class Policy: + def detect(self,tools): + im=tools.image('head').astype(np.int16);m=(im[:,:,0]>80)&(im[:,:,0]>1.6*im[:,:,1])&(im[:,:,0]>1.6*im[:,:,2]); y,x=np.where(m) + if len(x)<6:return None + w=x.max()-x.min()+1 + return ((x.min()+x.max())/2, float(y.mean()) if y.min()>0 else float(y.max()-w/2), np.sqrt(len(x)/np.pi) if y.min()>0 else w/2, y.min()==0) + def reset(self,obs,tools): + self.hold=np.array(tools.hold_action());v=self.detect(tools);self.stage=0;self.start=0 + if v is None:v=(37,10,6,True) + x,y,r,clipped=v; self.original=v + pos=obs['low_dim_obs'] + if clipped:dx=.10 if x<26 else .08 + elif r<5.72:dx=np.clip((35-y)*.0085,0,.18) + else:dx=0 + dy=np.clip((37-x)*.006,-.15,.15);self.goal=np.array([pos[18]+dx,pos[19]+dy]);self.pitch=-.6 + def act(self,obs,tools): + a=self.hold.copy();t=obs['t'];p=obs['low_dim_obs'] + if self.stage==0: + d=self.goal-p[18:20] + if np.linalg.norm(d)<.023 or t>130:self.stage=1;self.start=t + else: + v=np.clip(d*1.6,-.18,.18);speed=np.linalg.norm(v) + if speed<.08:v*=.08/max(speed,1e-6) + a[0:2]=v + elif self.stage==1: + if t-self.start>=45: + v=self.detect(tools) or self.original + self.pitch=np.clip(-.6+(v[1]-35)*.017,-1.4,-.3) + self.stage=2;self.start=t + else: + poses=[(0,-.1,1),(-.18,-.1,1.3),(.13,-.1,.7),(0,-.25,1),(-.18,-.25,1.3),(.13,-.25,.7),(0,.05,1),(-.18,.05,1.3)] + i=min((t-self.start)//95,len(poses)-1);dp,roll,el=poses[i];a[4:8]=[self.pitch+dp,roll,0,el] + return a diff --git a/policies/reach_target_single/gpt61terra-s3/episodes.csv b/policies/reach_target_single/gpt61terra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..9a9f79b821f04117bca183bb01033d098a73cd8f --- /dev/null +++ b/policies/reach_target_single/gpt61terra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,900,timeout,0 +620001,1,315,success,0 +620002,1,324,success,0 +620003,1,296,success,0 +620004,1,465,success,0 +620005,1,306,success,0 +620006,1,506,success,0 +620007,1,299,success,0 +620008,1,219,success,0 +620009,1,305,success,0 +620010,1,493,success,0 +620011,1,310,success,0 +620012,1,525,success,0 +620013,1,255,success,0 +620014,1,372,success,0 +620015,1,316,success,0 +620016,1,343,success,0 +620017,1,357,success,0 +620018,1,290,success,0 +620019,0,900,timeout,0 +620020,1,378,success,0 +620021,1,314,success,0 +620022,1,464,success,0 +620023,1,295,success,0 +620024,1,310,success,0 +620025,1,283,success,0 +620026,1,303,success,0 +620027,1,341,success,0 +620028,0,900,timeout,0 +620029,1,809,success,0 +620030,1,450,success,0 +620031,1,595,success,0 +620032,1,335,success,0 +620033,1,236,success,0 +620034,1,305,success,0 +620035,1,359,success,0 +620036,1,440,success,0 +620037,1,313,success,0 +620038,1,371,success,0 +620039,1,313,success,0 +620040,1,316,success,0 +620041,1,463,success,0 +620042,1,463,success,0 +620043,1,313,success,0 +620044,1,232,success,0 +620045,1,312,success,0 +620046,1,314,success,0 +620047,1,299,success,0 +620048,1,298,success,0 +620049,0,900,timeout,0 +620050,0,900,timeout,0 +620051,1,300,success,0 +620052,0,900,timeout,0 +620053,1,373,success,0 +620054,1,293,success,0 +620055,0,900,timeout,0 +620056,1,312,success,0 +620057,1,380,success,0 +620058,0,900,timeout,0 +620059,0,900,timeout,0 +620060,1,242,success,0 +620061,0,900,timeout,0 +620062,1,382,success,0 +620063,1,298,success,0 +620064,0,900,timeout,0 +620065,0,900,timeout,0 +620066,0,900,timeout,0 +620067,0,900,timeout,0 +620068,1,245,success,0 +620069,1,297,success,0 +620070,1,308,success,0 +620071,1,327,success,0 +620072,0,900,timeout,0 +620073,1,378,success,0 +620074,1,307,success,0 +620075,0,900,timeout,0 +620076,1,315,success,0 +620077,1,612,success,0 +620078,1,309,success,0 +620079,1,259,success,0 +620080,1,376,success,0 +620081,0,900,timeout,0 +620082,1,381,success,0 +620083,1,813,success,0 +620084,1,236,success,0 +620085,0,900,timeout,0 +620086,1,293,success,0 +620087,0,900,timeout,0 +620088,0,900,timeout,0 +620089,1,299,success,0 +620090,1,316,success,0 +620091,1,287,success,0 +620092,1,383,success,0 +620093,0,900,timeout,0 +620094,1,465,success,0 +620095,0,900,timeout,0 +620096,1,296,success,0 +620097,1,381,success,0 +620098,1,328,success,0 +620099,1,291,success,0 diff --git a/policies/reach_target_single/gpt61terra-s3/policy.py b/policies/reach_target_single/gpt61terra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..8342aa602fe7ad0e1fb8ba7a7baac2dd9dff365e --- /dev/null +++ b/policies/reach_target_single/gpt61terra-s3/policy.py @@ -0,0 +1,91 @@ +"""Deterministic visual reaching controller for the G1.""" + +import cv2 +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.phase_start = 0 + self.target = None + self.height = 0.74 + + @staticmethod + def ball(tools): + image = tools.image('head') + red = image[:, :, 0].astype(np.int16) + green = image[:, :, 1].astype(np.int16) + blue = image[:, :, 2].astype(np.int16) + mask = ((red > 70) & (red > 1.6 * green) & + (red > 1.5 * blue)).astype(np.uint8) + contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, + cv2.CHAIN_APPROX_SIMPLE) + if not contours: + return None + contour = max(contours, key=cv2.contourArea) + if cv2.contourArea(contour) < 5: + return None + (x, y), radius = cv2.minEnclosingCircle(contour) + return x, y, radius + + def act(self, obs, tools): + t = obs['t'] + pose = obs['low_dim_obs'] + action = self.hold.copy() + action[2] = self.height + + if self.phase == 0: + ball = self.ball(tools) + if ball is None or ball[1] - ball[2] < 0: + action[0] = 0.18 + else: + x, y, radius = ball + dx = np.clip((18.5 - y + 3.76 * (6.8 - radius)) / 148, + -0.28, 0.28) + dy = np.clip((32.5 - x) / 150, -0.2, 0.2) + self.target = (pose[18] + dx, pose[19] + dy) + self.phase = 1 + self.phase_start = t + elif self.phase == 1: + dx = self.target[0] - pose[18] + dy = self.target[1] - pose[19] + elapsed = t - self.phase_start + if ((elapsed > 25 and abs(dx) < 0.025 and abs(dy) < 0.025) + or elapsed > 180): + self.phase = 2 + self.phase_start = t + else: + velocity = np.array([dx, dy]) * 2.0 + speed = np.linalg.norm(velocity) + if speed > 0.22: + velocity *= 0.22 / speed + if 0 < speed < 0.065: + velocity *= 0.065 / speed + action[:2] = velocity + elif self.phase == 2: + elapsed = t - self.phase_start + if elapsed == 25: + ball = self.ball(tools) + if ball is not None: + self.height = np.clip(0.74 + (18.5 - ball[1]) / 95, + 0.52, 0.8) + if elapsed > 130: + self.phase = 3 + self.phase_start = t + else: + # Hold each reach long enough for both arm tracking and the + # required sustained contact; vary stance and approach angle. + poses = [ + [-0.8, 0, 0, 1], [-0.95, 0, 0, 1], + [-1.1, 0, 0, 1.3], [-0.95, 0, 0, 1], + [-0.95, 0, 0, 1], [-0.9, 0, -0.3, 0.8], + [-0.9, 0, 0.3, 0.8], [-0.95, 0, 0, 0.8], + [-1.1, 0, -0.5, 1.3], + ] + index = min((t - self.phase_start) // 75, len(poses) - 1) + action[4:8] = poses[index] + if index in (3, 4): + action[2] = max(0.52, self.height - 0.06) + return action diff --git a/policies/reach_target_single/gpt6sol-s1/episodes.csv b/policies/reach_target_single/gpt6sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8e52327704f9803a95faa2c0f80c63c0a4b155c5 --- /dev/null +++ b/policies/reach_target_single/gpt6sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,900,timeout,0 +620001,0,900,timeout,0 +620002,1,105,success,0 +620003,1,127,success,0 +620004,1,115,success,0 +620005,1,137,success,0 +620006,1,381,success,0 +620007,1,153,success,0 +620008,1,150,success,0 +620009,1,106,success,0 +620010,1,151,success,0 +620011,1,145,success,0 +620012,1,152,success,0 +620013,1,339,success,0 +620014,1,142,success,0 +620015,1,142,success,0 +620016,1,153,success,0 +620017,1,364,success,0 +620018,1,142,success,0 +620019,1,134,success,0 +620020,1,120,success,0 +620021,0,900,timeout,0 +620022,1,145,success,0 +620023,0,900,timeout,0 +620024,1,175,success,0 +620025,0,900,timeout,0 +620026,1,101,success,0 +620027,1,114,success,0 +620028,0,900,timeout,0 +620029,0,900,timeout,0 +620030,1,380,success,0 +620031,1,341,success,0 +620032,1,130,success,0 +620033,1,175,success,0 +620034,1,347,success,0 +620035,1,154,success,0 +620036,1,373,success,0 +620037,1,131,success,0 +620038,1,126,success,0 +620039,1,163,success,0 +620040,1,162,success,0 +620041,1,151,success,0 +620042,1,113,success,0 +620043,1,105,success,0 +620044,1,142,success,0 +620045,1,352,success,0 +620046,0,900,timeout,0 +620047,0,900,timeout,0 +620048,1,98,success,0 +620049,1,152,success,0 +620050,1,147,success,0 +620051,0,900,timeout,0 +620052,1,173,success,0 +620053,1,368,success,0 +620054,1,102,success,0 +620055,0,900,timeout,0 +620056,1,110,success,0 +620057,1,138,success,0 +620058,0,900,timeout,0 +620059,1,149,success,0 +620060,1,158,success,0 +620061,1,137,success,0 +620062,0,900,timeout,0 +620063,1,126,success,0 +620064,1,137,success,0 +620065,0,900,timeout,0 +620066,1,114,success,0 +620067,0,900,timeout,0 +620068,1,107,success,0 +620069,1,129,success,0 +620070,1,129,success,0 +620071,1,116,success,0 +620072,1,128,success,0 +620073,1,120,success,0 +620074,0,900,timeout,0 +620075,1,109,success,0 +620076,1,129,success,0 +620077,1,128,success,0 +620078,1,175,success,0 +620079,1,98,success,0 +620080,1,130,success,0 +620081,1,101,success,0 +620082,1,149,success,0 +620083,1,148,success,0 +620084,0,900,timeout,0 +620085,1,117,success,0 +620086,1,101,success,0 +620087,1,107,success,0 +620088,1,166,success,0 +620089,0,900,timeout,0 +620090,1,101,success,0 +620091,1,139,success,0 +620092,1,153,success,0 +620093,0,900,timeout,0 +620094,1,149,success,0 +620095,0,900,timeout,0 +620096,1,156,success,0 +620097,1,155,success,0 +620098,1,106,success,0 +620099,1,135,success,0 diff --git a/policies/reach_target_single/gpt6sol-s1/policy.py b/policies/reach_target_single/gpt6sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..552c9fa0f3785ad18faba977ca4bce92c6b78e0a --- /dev/null +++ b/policies/reach_target_single/gpt6sol-s1/policy.py @@ -0,0 +1,70 @@ +"""Visual approach and left hand reach for the red sphere.""" + +import cv2 +import numpy as np + + +def red_ball(image): + rgb = image.astype(np.int16) + r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2] + mask = ((r > 55) & (r * 10 > g * 14) & (r * 10 > b * 13)).astype(np.uint8) + count, labels, stats, centers = cv2.connectedComponentsWithStats(mask) + if count < 2: + return None + i = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + if stats[i, cv2.CC_STAT_AREA] < 7: + return None + return float(centers[i, 0]), float(centers[i, 1]), int(stats[i, cv2.CC_STAT_AREA]) + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = 'approach' + self.phase_t = 0 + self.smooth_x = None + self.mode = None + self.first_200 = None + self.stop_ball = None + + def act(self, obs, tools): + t = int(obs['t']) + raw = self.hold.copy() + raw[0] = raw[1] = raw[3] = 0 + if self.phase == 'approach': + ball = red_ball(tools.image('head')) + if ball is not None: + self.smooth_x = ball[0] if self.smooth_x is None else 0.8 * self.smooth_x + 0.2 * ball[0] + if self.first_200 is None and ball[2] >= 200: + self.first_200 = ball + if 23.85 <= ball[1] <= 24.2: + self.mode = 'near_high' + else: + self.mode = 'high' if ball[1] < 25 else ('middle' if ball[1] < 47 else 'low') + if (self.mode == 'high' and ball is not None and ball[2] >= 250) or self.mode in ('near_high', 'middle', 'low'): + self.phase = 'reach' + self.phase_t = t + self.stop_ball = ball + else: + raw[0] = 0.25 + if self.smooth_x is not None: + error = self.smooth_x - 48 + raw[1] = np.clip(-0.012 * error, -0.25, 0.25) if abs(error) > 4 else 0 + return raw + + if self.phase == 'reach': + reach_age = t - self.phase_t + if self.mode == 'high': + raw[2] = 0.74 + raw[4:11] = [-0.2 if reach_age < 250 else -0.35, 0, -0.55, 0, 0, 0, 0] + elif self.mode == 'near_high': + raw[2] = 0.74 + raw[4:11] = [-0.2 if reach_age < 250 else -0.35, 0, -0.55, 0, 0, 0, 0] + elif self.mode == 'middle': + y = self.first_200[1] + raw[2] = 0.74 if (28 <= y < 31 or reach_age >= 250 and y < 32) else 0.68 + raw[4:11] = [-0.2, 0, -0.55, 0, 0, 0, 0] + else: + raw[2] = 0.68 + raw[4:11] = [0.2 if reach_age >= 250 else 0, 0, -0.7, 0, 0, 0, 0] + return raw diff --git a/policies/reach_target_single/gpt6sol-s2/episodes.csv b/policies/reach_target_single/gpt6sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..c04f0e6ad9c03e99ab207b726441e2282312ba94 --- /dev/null +++ b/policies/reach_target_single/gpt6sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,295,success,0 +620001,1,156,success,0 +620002,0,900,timeout,0 +620003,0,900,timeout,0 +620004,1,312,success,0 +620005,0,900,timeout,0 +620006,1,297,success,0 +620007,1,150,success,0 +620008,1,236,success,0 +620009,0,900,timeout,0 +620010,1,236,success,0 +620011,0,900,timeout,0 +620012,1,299,success,0 +620013,0,900,timeout,0 +620014,1,498,success,0 +620015,0,900,timeout,0 +620016,1,147,success,0 +620017,1,298,success,0 +620018,0,900,timeout,0 +620019,1,296,success,0 +620020,1,150,success,0 +620021,0,900,timeout,0 +620022,1,237,success,0 +620023,0,900,timeout,0 +620024,1,150,success,0 +620025,0,900,timeout,0 +620026,0,900,timeout,0 +620027,0,900,timeout,0 +620028,1,299,success,0 +620029,0,900,timeout,0 +620030,1,300,success,0 +620031,0,900,timeout,0 +620032,0,900,timeout,0 +620033,1,226,success,0 +620034,0,900,timeout,0 +620035,1,149,success,0 +620036,1,297,success,0 +620037,0,900,timeout,0 +620038,1,237,success,0 +620039,0,900,timeout,0 +620040,1,150,success,0 +620041,1,152,success,0 +620042,1,296,success,0 +620043,0,900,timeout,0 +620044,1,345,success,0 +620045,0,900,timeout,0 +620046,0,900,timeout,0 +620047,1,298,success,0 +620048,0,900,timeout,0 +620049,1,154,success,0 +620050,1,146,success,0 +620051,0,900,timeout,0 +620052,0,900,timeout,0 +620053,1,297,success,0 +620054,0,900,timeout,0 +620055,1,299,success,0 +620056,0,900,timeout,0 +620057,1,236,success,0 +620058,1,666,success,0 +620059,1,297,success,0 +620060,1,275,success,0 +620061,1,340,success,0 +620062,1,335,success,0 +620063,0,900,timeout,0 +620064,1,498,success,0 +620065,1,299,success,0 +620066,0,900,timeout,0 +620067,1,298,success,0 +620068,0,900,timeout,0 +620069,0,900,timeout,0 +620070,0,900,timeout,0 +620071,0,900,timeout,0 +620072,1,149,success,0 +620073,1,150,success,0 +620074,1,275,success,0 +620075,0,900,timeout,0 +620076,0,900,timeout,0 +620077,0,900,timeout,0 +620078,1,357,success,0 +620079,1,272,success,0 +620080,1,151,success,0 +620081,0,900,timeout,0 +620082,1,153,success,0 +620083,1,151,success,0 +620084,0,900,timeout,0 +620085,0,900,timeout,0 +620086,0,900,timeout,0 +620087,0,900,timeout,0 +620088,0,900,timeout,0 +620089,0,900,timeout,0 +620090,0,900,timeout,0 +620091,0,900,timeout,0 +620092,1,275,success,0 +620093,1,297,success,0 +620094,1,342,success,0 +620095,1,301,success,0 +620096,1,149,success,0 +620097,1,152,success,0 +620098,0,900,timeout,0 +620099,0,900,timeout,0 diff --git a/policies/reach_target_single/gpt6sol-s2/policy.py b/policies/reach_target_single/gpt6sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..752f931c5cc676a96006b8f8c547026c4c74e602 --- /dev/null +++ b/policies/reach_target_single/gpt6sol-s2/policy.py @@ -0,0 +1,98 @@ +"""Hand written visual servo controller for touching the red sphere.""" + +import cv2 +import numpy as np + + +def red_blob(image): + hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) + mask = cv2.inRange(hsv, (0, 90, 40), (12, 255, 255)) + mask |= cv2.inRange(hsv, (170, 90, 40), (179, 255, 255)) + count, labels, stats, centers = cv2.connectedComponentsWithStats(mask) + if count <= 1: + return None + k = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA]) + if stats[k, cv2.CC_STAT_AREA] < 5: + return None + return np.array([centers[k, 0], centers[k, 1], stats[k, cv2.CC_STAT_AREA]], dtype=np.float64) + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.yaw0 = float(obs["low_dim_obs"][21]) + self.stage = "approach" + self.stable = 0 + self.last_ball = None + self.missing = 0 + self.reach_start = 0 + self.reach_height = .62 + self.nudge_goal = None + + def act(self, obs, tools): + t = int(obs["t"]) + raw = self.hold.copy() + raw[18] = 0.0 + if self.stage == "approach": + blob = red_blob(tools.image("head")) + if blob is not None: + if self.last_ball is None: + self.last_ball = blob + else: + self.last_ball = .7 * self.last_ball + .3 * blob + self.missing = 0 + else: + self.missing += 1 + if self.last_ball is not None: + x, y = self.last_ball[:2] + ex = x - 24.0 + ey = 38.0 - y + raw[0] = np.clip(.012 * ey, -.26, .26) + raw[1] = np.clip(-.012 * ex, -.26, .26) + if abs(raw[0]) < .065: + raw[0] = 0 + if abs(raw[1]) < .065: + raw[1] = 0 + if abs(ex) < 3.5 and abs(ey) < 3.5: + self.stable += 1 + else: + self.stable = 0 + elif t < 100: + raw[0] = .16 + raw[3] = np.clip(-2.0 * (float(obs["low_dim_obs"][21]) - self.yaw0), -.25, .25) + if self.stable >= 10 or t >= 175: + area = float(self.last_ball[2]) if self.last_ball is not None else 120. + self.reach_height = float(np.clip(.62 + .018 * (np.sqrt(area) - 11.), .60, .74)) + if area < 160: + q = obs["low_dim_obs"] + self.nudge_goal = (float(q[18]) + .035, float(q[19])) + self.stage = "nudge" + self.nudge_start = t + else: + self.stage = "reach" + self.reach_start = t + if self.stage == "nudge": + q = obs["low_dim_obs"] + ex = self.nudge_goal[0] - float(q[18]) + ey = self.nudge_goal[1] - float(q[19]) + yaw = float(q[21]) + c, s = np.cos(yaw), np.sin(yaw) + bx, by = c * ex + s * ey, -s * ex + c * ey + raw[0] = np.clip(3 * bx, -.2, .2) if abs(bx) > .01 else 0 + raw[1] = np.clip(3 * by, -.2, .2) if abs(by) > .01 else 0 + raw[3] = np.clip(-2 * (yaw - self.yaw0), -.2, .2) + if t - self.nudge_start >= 60: + self.stage = "reach" + self.reach_start = t + if self.stage == "reach": + raw[:4] = [0, 0, self.reach_height, 0] + raw[4:11] = [-.2, 0, 0, 0, 0, 0, 0] + if t - self.reach_start > 130: + self.stage = "search" + if self.stage == "search": + phase = ((t - self.reach_start - 130) // 80) % 7 + heights = [0, 0, -.025, .025, 0, -.045, .045] + pitches = [-.12, -.27, -.2, -.2, -.4, -.3, -.1] + raw[:4] = [0, 0, np.clip(self.reach_height + heights[phase], .4, .8), 0] + raw[4:11] = [pitches[phase], 0, 0, 0, 0, 0, 0] + return raw diff --git a/policies/reach_target_single/gpt6sol-s3/episodes.csv b/policies/reach_target_single/gpt6sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..47258c80e84b9c285fc007d28057e108cae46150 --- /dev/null +++ b/policies/reach_target_single/gpt6sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,194,success,0 +620001,0,900,timeout,0 +620002,0,900,timeout,0 +620003,0,900,timeout,0 +620004,1,581,success,0 +620005,0,900,timeout,0 +620006,1,264,success,0 +620007,0,900,timeout,0 +620008,1,238,success,0 +620009,0,900,timeout,0 +620010,1,154,success,0 +620011,0,900,timeout,0 +620012,1,668,success,0 +620013,0,900,timeout,0 +620014,1,259,success,0 +620015,1,167,success,0 +620016,1,222,success,0 +620017,1,569,success,0 +620018,0,900,timeout,0 +620019,1,266,success,0 +620020,1,164,success,0 +620021,1,166,success,0 +620022,1,583,success,0 +620023,0,900,timeout,0 +620024,0,900,timeout,0 +620025,0,900,timeout,0 +620026,0,900,timeout,0 +620027,0,900,timeout,0 +620028,0,900,timeout,0 +620029,1,650,success,0 +620030,1,487,success,0 +620031,0,900,timeout,0 +620032,0,900,timeout,0 +620033,0,900,timeout,0 +620034,1,246,success,0 +620035,1,184,success,0 +620036,1,259,success,0 +620037,0,900,timeout,0 +620038,0,900,timeout,0 +620039,1,182,success,0 +620040,1,172,success,0 +620041,1,176,success,0 +620042,1,191,success,0 +620043,0,900,timeout,0 +620044,0,900,timeout,0 +620045,1,162,success,0 +620046,1,161,success,0 +620047,1,735,success,0 +620048,0,900,timeout,0 +620049,1,174,success,0 +620050,1,192,success,0 +620051,0,900,timeout,0 +620052,0,900,timeout,0 +620053,1,258,success,0 +620054,0,900,timeout,0 +620055,0,900,timeout,0 +620056,0,900,timeout,0 +620057,1,195,success,0 +620058,1,266,success,0 +620059,1,605,success,0 +620060,1,163,success,0 +620061,1,609,success,0 +620062,1,356,success,0 +620063,0,900,timeout,0 +620064,1,201,success,0 +620065,1,591,success,0 +620066,0,900,timeout,0 +620067,1,442,success,0 +620068,1,169,success,0 +620069,0,900,timeout,0 +620070,0,900,timeout,0 +620071,0,900,timeout,0 +620072,1,167,success,0 +620073,1,164,success,0 +620074,0,900,timeout,0 +620075,0,900,timeout,0 +620076,0,900,timeout,0 +620077,0,900,timeout,0 +620078,0,900,timeout,0 +620079,1,157,success,0 +620080,1,180,success,0 +620081,0,900,timeout,0 +620082,1,166,success,0 +620083,1,190,success,0 +620084,0,900,timeout,0 +620085,0,900,timeout,0 +620086,0,900,timeout,0 +620087,0,900,timeout,0 +620088,0,900,timeout,0 +620089,0,900,timeout,0 +620090,0,900,timeout,0 +620091,0,900,timeout,0 +620092,1,213,success,0 +620093,1,609,success,0 +620094,1,674,success,0 +620095,0,900,timeout,0 +620096,1,266,success,0 +620097,1,170,success,0 +620098,0,900,timeout,0 +620099,0,900,timeout,0 diff --git a/policies/reach_target_single/gpt6sol-s3/policy.py b/policies/reach_target_single/gpt6sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b345751de4201b0695f5a2795b5c6b1b59cf5e81 --- /dev/null +++ b/policies/reach_target_single/gpt6sol-s3/policy.py @@ -0,0 +1,83 @@ +"""Deterministic visual control for touching the red sphere with the left hand.""" + +import cv2 +import numpy as np + + +def red_blob(image): + hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) + mask = (((hsv[:, :, 0] <= 12) | (hsv[:, :, 0] >= 170)) & + (hsv[:, :, 1] >= 105) & (hsv[:, :, 2] >= 55)).astype(np.uint8) + count, _, stats, centers = cv2.connectedComponentsWithStats(mask) + if count < 2: + return None + i = 1 + np.argmax(stats[1:, cv2.CC_STAT_AREA]) + area = int(stats[i, cv2.CC_STAT_AREA]) + if area < 12: + return None + return float(centers[i, 0]), float(centers[i, 1]), area + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = "approach" + self.stop_t = 0 + self.reach_t = 0 + self.pitch = 0.15 + self.yaw = -0.55 + self.head = None + self.corrected = False + + def act(self, obs, tools): + t = int(obs["t"]) + action = self.hold.copy() + action[18] = 0.0 + + if self.phase == "approach": + if t % 2 == 0 or self.head is None: + self.head = red_blob(tools.image("head")) + if (self.head is not None and self.head[1] >= 43.0) or t >= 240: + self.phase = "settle" + self.stop_t = t + else: + action[0] = 0.15 + return action + + if self.phase == "settle": + if t < self.stop_t + 20: + return action + self.head = red_blob(tools.image("head")) + if self.head is not None: + x, _, area = self.head + self.pitch = float(np.clip(0.15 - 0.002 * (area - 180), -0.65, 0.5)) + self.yaw = float(np.clip(-0.55 + 0.012 * (46.0 - x), -1.2, 0.5)) + self.reach_t = t + self.phase = "reach" + + u = t - self.reach_t + if u >= 110 and not self.corrected: + wrist = red_blob(tools.image("left_wrist")) + if wrist is not None and wrist[2] < 6000: + self.yaw = float(np.clip(self.yaw + 0.005 * (40.0 - wrist[0]), -1.2, 0.5)) + self.corrected = True + + # First allow the arm to settle, then test nearby base positions. Each + # position is held for over one second, as required by the task. + if u >= 175: + v = u - 175 + depth = v // 82 + within = v % 82 + if depth < 6 and within < 17: + action[0] = 0.08 + if depth >= 6: + # Nearby vertical poses at the final base position. + pitch_offsets = (-0.15, 0.15, -0.3) + j = min((v - 6 * 82) // 68, len(pitch_offsets) - 1) + action[4] = float(np.clip(self.pitch + pitch_offsets[j], -0.8, 0.7)) + else: + action[4] = self.pitch + else: + action[4] = self.pitch + action[6] = self.yaw + return action diff --git a/policies/reach_target_single/kimi31pro-s1/episodes.csv b/policies/reach_target_single/kimi31pro-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..e61b1e5fdbc7f15800164e7092b80dc664366124 --- /dev/null +++ b/policies/reach_target_single/kimi31pro-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,179,success,0 +620001,1,378,success,0 +620002,0,900,timeout,0 +620003,1,336,success,0 +620004,0,900,timeout,0 +620005,1,660,success,0 +620006,1,455,success,0 +620007,0,900,timeout,0 +620008,1,208,success,0 +620009,0,900,timeout,0 +620010,1,143,success,0 +620011,0,900,timeout,0 +620012,0,900,timeout,0 +620013,1,744,success,0 +620014,1,271,success,0 +620015,0,900,timeout,0 +620016,1,138,success,0 +620017,1,345,success,0 +620018,0,900,timeout,0 +620019,1,227,success,0 +620020,1,164,success,0 +620021,0,900,timeout,0 +620022,0,900,timeout,0 +620023,1,339,success,0 +620024,1,389,success,0 +620025,1,564,success,0 +620026,1,494,success,0 +620027,0,900,timeout,0 +620028,0,900,timeout,0 +620029,0,900,timeout,0 +620030,0,900,timeout,0 +620031,1,339,success,0 +620032,0,900,timeout,0 +620033,1,383,success,0 +620034,0,900,timeout,0 +620035,1,388,success,0 +620036,1,365,success,0 +620037,0,900,timeout,0 +620038,1,184,success,0 +620039,1,373,success,0 +620040,0,900,timeout,0 +620041,1,182,success,0 +620042,1,235,success,0 +620043,0,900,timeout,0 +620044,1,378,success,0 +620045,1,330,success,0 +620046,0,900,timeout,0 +620047,0,900,timeout,0 +620048,1,331,success,0 +620049,1,142,success,0 +620050,1,191,success,0 +620051,1,432,success,0 +620052,0,900,timeout,0 +620053,1,296,success,0 +620054,1,409,success,0 +620055,0,900,timeout,0 +620056,0,900,timeout,0 +620057,1,161,success,0 +620058,1,178,success,0 +620059,0,900,timeout,0 +620060,0,900,timeout,0 +620061,1,360,success,0 +620062,1,293,success,0 +620063,0,900,timeout,0 +620064,1,228,success,0 +620065,0,900,timeout,0 +620066,0,900,timeout,0 +620067,0,900,timeout,0 +620068,0,900,timeout,0 +620069,0,900,timeout,0 +620070,0,900,timeout,0 +620071,0,900,timeout,0 +620072,1,162,success,0 +620073,1,161,success,0 +620074,1,376,success,0 +620075,0,900,timeout,0 +620076,0,900,timeout,0 +620077,0,900,timeout,0 +620078,1,378,success,0 +620079,0,900,timeout,0 +620080,1,718,success,0 +620081,1,508,success,0 +620082,1,169,success,0 +620083,1,149,success,0 +620084,1,350,success,0 +620085,0,900,timeout,0 +620086,1,503,success,0 +620087,0,900,timeout,0 +620088,1,512,success,0 +620089,1,496,success,0 +620090,1,344,success,0 +620091,1,350,success,0 +620092,1,167,success,0 +620093,0,900,timeout,0 +620094,0,900,timeout,0 +620095,0,900,timeout,0 +620096,1,350,success,0 +620097,1,181,success,0 +620098,0,900,timeout,0 +620099,0,900,timeout,0 diff --git a/policies/reach_target_single/kimi31pro-s1/policy.py b/policies/reach_target_single/kimi31pro-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2013fcfdc007a8d74a709d3927ea9e41722087cb --- /dev/null +++ b/policies/reach_target_single/kimi31pro-s1/policy.py @@ -0,0 +1,98 @@ +"""Deterministic vision-guided reaching policy for the red sphere.""" + +import numpy as np + + +def _red_sphere(image): + """Return red-mask area and centroid in the small robot camera image.""" + f = np.asarray(image, dtype=np.float32) + r, g, b = f[..., 0], f[..., 1], f[..., 2] + mask = (r > 45) & (r > 1.35 * g) & (r > 1.25 * b) & ((r - g) > 25) + ys, xs = np.nonzero(mask) + if len(xs) == 0: + return 0, 42.0, 42.0 + return len(xs), float(xs.mean()), float(ys.mean()) + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.arm_start = self.hold[4:11].copy() + self.approach_done_t = None + self.final_elbow = 1.2 + self.high_target = False + self.high_yaw = -0.6 + + def act(self, obs, tools): + raw = self.hold.copy() + t = int(obs["t"]) + + if self.approach_done_t is None: + area, cx, _ = _red_sphere(tools.image("head")) + if area >= 165: + self.approach_done_t = t + else: + raw[0] = 0.12 + raw[3] = float(np.clip(0.012 * (45.0 - cx), -0.15, 0.15)) + return raw + + # Let the base stop before moving the arm through its reaching path. + reach_t = t - self.approach_done_t - 31 + if reach_t < 0: + return raw + + # Camera height selects the unobstructed raised-shoulder branch for + # high targets, or the lower contact-limited branch used for low ones. + if reach_t == 0: + area, cx, cy = _red_sphere(tools.image("head")) + self.high_target = area > 0 and cy < 22.0 + if area > 0 and self.high_target: + self.high_yaw = float(np.clip(-0.6 + 0.02 * (40.5 - cx), -1.0, -0.2)) + self.final_elbow = float(np.clip(1.085 + 0.015 * cy, 0.8, 1.5)) + elif area > 0: + self.final_elbow = float(np.clip(1.2 + 0.015 * (cy - 41.2), 0.45, 1.45)) + + if self.high_target: + if reach_t < 320: + elbows = (0.4, 0.7, 1.0, self.final_elbow) + stage = min(3, reach_t // 80) + local_t = reach_t - stage * 80 + elbow = elbows[stage] + previous_elbow = elbows[stage - 1] if stage else 0.0 + yaw = self.high_yaw + previous_yaw = yaw + else: + # Nearby objects can need a different palm-to-camera offset. + # Try a small deterministic set of inward-yaw poses, holding + # each long enough for the one-second contact condition. + offsets = (0.15, 0.30, 0.45, -0.15, 0.60, -0.30) + search_t = reach_t - 320 + stage = min(len(offsets) - 1, search_t // 80) + local_t = search_t - stage * 80 + elbow = self.final_elbow + previous_elbow = elbow + yaw = self.high_yaw + offsets[stage] + previous_yaw = self.high_yaw + (offsets[stage - 1] if stage else 0.0) + target = np.array([-1.2, 0.0, yaw, elbow, 0.0, 0.0, 0.0], dtype=np.float32) + start = np.array([-1.2, 0.0, previous_yaw, previous_elbow, 0.0, 0.0, 0.0], dtype=np.float32) + else: + # Staging this path avoids a contact-limited shoulder configuration + # that a direct jump to the final pose can enter. + stage = min(2, reach_t // 85) + local_t = reach_t - stage * 85 + if stage == 0: + elbow = 1.0 + previous_elbow = 0.0 + elif stage == 1: + elbow = 0.5 * (1.0 + self.final_elbow) + previous_elbow = 1.0 + else: + elbow = self.final_elbow + previous_elbow = 0.5 * (1.0 + self.final_elbow) + target = np.array([-1.2, -0.4, 0.0, elbow, 0.0, 0.0, 0.0], dtype=np.float32) + start = np.array([-1.2, -0.4, 0.0, previous_elbow, 0.0, 0.0, 0.0], dtype=np.float32) + if reach_t < 80: + start = self.arm_start + u = min(1.0, (local_t + 1) / 30.0) + raw[4:11] = (1.0 - u) * start + u * target + return raw diff --git a/policies/reach_target_single/kimi31pro-s2/episodes.csv b/policies/reach_target_single/kimi31pro-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..3ed60ce6921c4944635cc23fa5ee76ca507bc7a6 --- /dev/null +++ b/policies/reach_target_single/kimi31pro-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,180,success,0 +620001,1,201,success,0 +620002,1,294,success,0 +620003,1,253,success,0 +620004,1,180,success,0 +620005,1,273,success,0 +620006,1,182,success,0 +620007,1,612,success,0 +620008,1,154,success,0 +620009,1,281,success,0 +620010,1,270,success,0 +620011,1,287,success,0 +620012,1,216,success,0 +620013,0,900,timeout,0 +620014,1,181,success,0 +620015,1,309,success,0 +620016,1,145,success,0 +620017,1,169,success,0 +620018,1,297,success,0 +620019,1,180,success,0 +620020,1,181,success,0 +620021,1,274,success,0 +620022,0,900,timeout,0 +620023,0,900,timeout,0 +620024,1,340,success,0 +620025,1,378,success,0 +620026,1,511,success,0 +620027,1,277,success,0 +620028,0,900,timeout,0 +620029,0,900,timeout,0 +620030,1,184,success,0 +620031,0,900,timeout,0 +620032,1,493,success,0 +620033,1,608,success,0 +620034,1,276,success,0 +620035,1,172,success,0 +620036,1,173,success,0 +620037,1,283,success,0 +620038,0,900,timeout,0 +620039,1,286,success,0 +620040,1,263,success,0 +620041,1,183,success,0 +620042,1,177,success,0 +620043,1,519,success,0 +620044,0,900,timeout,0 +620045,1,280,success,0 +620046,1,274,success,0 +620047,0,900,timeout,0 +620048,1,140,success,0 +620049,1,165,success,0 +620050,1,182,success,0 +620051,0,900,timeout,0 +620052,1,536,success,0 +620053,1,154,success,0 +620054,1,502,success,0 +620055,0,900,timeout,0 +620056,1,293,success,0 +620057,0,900,timeout,0 +620058,1,135,success,0 +620059,1,208,success,0 +620060,1,307,success,0 +620061,1,204,success,0 +620062,1,182,success,0 +620063,1,333,success,0 +620064,0,900,timeout,0 +620065,1,186,success,0 +620066,1,307,success,0 +620067,1,205,success,0 +620068,1,313,success,0 +620069,1,538,success,0 +620070,1,292,success,0 +620071,0,900,timeout,0 +620072,1,170,success,0 +620073,1,180,success,0 +620074,1,296,success,0 +620075,1,311,success,0 +620076,1,377,success,0 +620077,1,292,success,0 +620078,1,341,success,0 +620079,1,307,success,0 +620080,1,182,success,0 +620081,1,506,success,0 +620082,1,184,success,0 +620083,1,165,success,0 +620084,0,900,timeout,0 +620085,1,188,success,0 +620086,1,535,success,0 +620087,1,522,success,0 +620088,1,539,success,0 +620089,0,900,timeout,0 +620090,1,289,success,0 +620091,1,333,success,0 +620092,1,191,success,0 +620093,1,203,success,0 +620094,0,900,timeout,0 +620095,0,900,timeout,0 +620096,1,162,success,0 +620097,1,183,success,0 +620098,1,272,success,0 +620099,1,340,success,0 diff --git a/policies/reach_target_single/kimi31pro-s2/policy.py b/policies/reach_target_single/kimi31pro-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..5e6282319d80f94f94a7526ab366e987f651e377 --- /dev/null +++ b/policies/reach_target_single/kimi31pro-s2/policy.py @@ -0,0 +1,97 @@ +"""Hand-written visual reaching controller for the Unitree G1.""" + +import cv2 +import numpy as np + + +class Policy: + """Approach the red target, then touch it with the left hand.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.reach_start = None + self.near_count = 0 + self.last_red = (0.0, 42.0, 20.0) + self.high_target = False + self.pose = np.array( + [-0.5, 0.0, -0.4, 0.8, 0.0, 0.0, 0.0], dtype=np.float32 + ) + + @staticmethod + def red_target(image): + """Return the area and centroid of the red sphere in an RGB image.""" + hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) + dark_red = cv2.inRange(hsv, np.array([0, 100, 50]), np.array([10, 255, 255])) + bright_red = cv2.inRange( + hsv, np.array([170, 100, 50]), np.array([179, 255, 255]) + ) + mask = dark_red | bright_red + count, _, stats, centroids = cv2.connectedComponentsWithStats(mask) + if count <= 1: + return None + component = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + area = int(stats[component, cv2.CC_STAT_AREA]) + if area < 5: + return None + center = centroids[component] + return float(area), float(center[0]), float(center[1]) + + def act(self, obs, tools): + raw = self.hold.copy() + t = int(obs["t"]) + + if self.reach_start is None: + red = self.red_target(tools.image("head")) + if red is not None: + self.last_red = red + area, cx, _ = self.last_red + + if t >= 20: + raw[0] = 0.24 if area < 125.0 else (0.12 if area <= 150.0 else 0.0) + raw[3] = np.clip(0.020 * (42.0 - cx), -0.30, 0.30) + centered = abs(cx - 42.0) < 3.0 + self.near_count = self.near_count + 1 if area > 150.0 and centered else 0 + if self.near_count >= 4 or t > 180: + self.reach_start = t + self.pose[0] = np.clip(-0.5 + 0.011 * (self.last_red[2] - 42.0), -1.15, -0.25) + self.high_target = self.last_red[2] < 12.0 + raw[0] = 0.0 + raw[3] = 0.0 + else: + elapsed = t - self.reach_start + blend = min(1.0, elapsed / 70.0) + raw[4:11] = self.pose * blend + if 130 <= elapsed < 200: + raw[0] = 0.08 + if self.high_target and 300 <= elapsed < 400: + correction = min(1.0, (elapsed - 300) / 30.0) + raw[4] = self.pose[0] - 0.10 * correction + raw[6] = self.pose[2] + 0.10 * correction + if elapsed >= 400: + # Sweep the hand left in small increments, dwelling at each pose. + level = min(4, (elapsed - 400) // 80) + phase = (elapsed - 400) % 80 + yaw_correction = 0.2 + 0.1 * level + if level == 0: + pitch_correction, previous_pitch = -0.05, -0.10 + yaw_correction, previous_yaw = 0.20, 0.10 + elif level == 1: + pitch_correction, previous_pitch = 0.08, -0.05 + yaw_correction, previous_yaw = 0.25, 0.20 + elif level == 2: + pitch_correction, previous_pitch = -0.15, 0.08 + yaw_correction, previous_yaw = 0.25, 0.25 + elif level == 3: + pitch_correction, previous_pitch = -0.15, -0.15 + yaw_correction, previous_yaw = 0.15, 0.25 + else: + pitch_correction, previous_pitch = 0.18, -0.15 + yaw_correction, previous_yaw = 0.25, 0.15 + blend = min(1.0, phase / 30.0) + if level == 0: + raw[4] = self.pose[0] - 0.05 + else: + raw[4] = self.pose[0] + previous_pitch + (pitch_correction - previous_pitch) * blend + raw[6] = self.pose[2] + previous_yaw + (yaw_correction - previous_yaw) * blend + + return raw diff --git a/policies/reach_target_single/kimi31pro-s3/episodes.csv b/policies/reach_target_single/kimi31pro-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..f0de8c8cd3e6663a8ce53bc215631063aa8a8abd --- /dev/null +++ b/policies/reach_target_single/kimi31pro-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,209,success,0 +620001,1,184,success,0 +620002,0,900,timeout,0 +620003,0,900,timeout,0 +620004,1,221,success,0 +620005,1,189,success,0 +620006,0,900,timeout,0 +620007,1,181,success,0 +620008,1,187,success,0 +620009,0,900,timeout,0 +620010,1,151,success,0 +620011,1,182,success,0 +620012,1,529,success,0 +620013,1,173,success,0 +620014,0,900,timeout,0 +620015,0,900,timeout,0 +620016,1,180,success,0 +620017,1,156,success,0 +620018,0,900,timeout,0 +620019,1,181,success,0 +620020,1,217,success,0 +620021,1,189,success,0 +620022,1,179,success,0 +620023,1,209,success,0 +620024,1,211,success,0 +620025,1,178,success,0 +620026,1,153,success,0 +620027,1,186,success,0 +620028,0,900,timeout,0 +620029,0,900,timeout,0 +620030,0,900,timeout,0 +620031,1,150,success,0 +620032,0,900,timeout,0 +620033,1,212,success,0 +620034,1,185,success,0 +620035,1,180,success,0 +620036,0,900,timeout,0 +620037,0,900,timeout,0 +620038,1,213,success,0 +620039,1,179,success,0 +620040,1,179,success,0 +620041,1,212,success,0 +620042,1,221,success,0 +620043,1,162,success,0 +620044,1,186,success,0 +620045,1,139,success,0 +620046,1,281,success,0 +620047,1,171,success,0 +620048,1,151,success,0 +620049,1,178,success,0 +620050,1,222,success,0 +620051,1,153,success,0 +620052,1,221,success,0 +620053,1,245,success,0 +620054,1,197,success,0 +620055,0,900,timeout,0 +620056,0,900,timeout,0 +620057,1,181,success,0 +620058,1,215,success,0 +620059,1,269,success,0 +620060,1,185,success,0 +620061,1,262,success,0 +620062,1,215,success,0 +620063,0,900,timeout,0 +620064,1,181,success,0 +620065,0,900,timeout,0 +620066,1,213,success,0 +620067,1,214,success,0 +620068,1,181,success,0 +620069,1,180,success,0 +620070,0,900,timeout,0 +620071,0,900,timeout,0 +620072,1,180,success,0 +620073,1,180,success,0 +620074,1,248,success,0 +620075,1,184,success,0 +620076,1,232,success,0 +620077,0,900,timeout,0 +620078,1,182,success,0 +620079,1,185,success,0 +620080,1,185,success,0 +620081,1,179,success,0 +620082,1,216,success,0 +620083,1,162,success,0 +620084,1,160,success,0 +620085,1,213,success,0 +620086,1,210,success,0 +620087,1,179,success,0 +620088,1,200,success,0 +620089,1,155,success,0 +620090,0,900,timeout,0 +620091,0,900,timeout,0 +620092,1,214,success,0 +620093,1,216,success,0 +620094,1,215,success,0 +620095,0,900,timeout,0 +620096,1,184,success,0 +620097,1,214,success,0 +620098,1,165,success,0 +620099,1,163,success,0 diff --git a/policies/reach_target_single/kimi31pro-s3/policy.py b/policies/reach_target_single/kimi31pro-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..7bb8a8f0028ad3f8f0d2419016626d78ff75c3b7 --- /dev/null +++ b/policies/reach_target_single/kimi31pro-s3/policy.py @@ -0,0 +1,256 @@ +"""Deterministic, camera-guided left-hand reaching policy for the G1.""" + +import cv2 +import numpy as np + + +class Policy: + """Track the red target and the left hand in the head camera.""" + + # Small deterministic contact maneuvers around a visually aligned pose. + SEARCH = ( + (0.0, 0.0, 0.0, 0.0, 0.6, 0), + (0.0, 0.0, 0.8, 0.0, 0.6, 0), + (0.0, 0.0, 0.4, 0.0, 1.0, 0), + (0.03, -0.05, 0.4, 0.0, 0.6, 0), + (0.0, 0.0, 0.4, -0.10, 0.6, 0), + (0.0, 0.0, 0.4, 0.10, 0.6, 0), + (0.0, 0.0, 0.4, 0.0, 0.6, -25), + (-0.03, -0.05, 0.4, 0.0, 0.6, 0), + (-0.08, 0.0, 0.4, 0.0, 0.6, 0), + (0.08, 0.0, 0.4, 0.0, 0.6, 0), + (0.0, 0.0, 0.4, 0.0, 0.6, 30), + (0.0, -0.15, 0.4, 0.0, 0.6, 0), + (0.0, 0.15, 0.4, 0.0, 0.6, 0), + ) + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.q = self.hold[4:11].astype(float).copy() + self.prepose = np.array([-0.8, 0.0, -0.6, 0.8, 0.0, 0.0, 0.0]) + self.target = None + self.hand = None + self.radius = None + self.close_time = None + self.stage = "raise" + self.stage_t = 0 + self.locked_q = self.q.copy() + self.error_filtered = None + self.full_visible = False + self.center_required = False + self.search_index = 0 + self.search_from = self.q.copy() + self.search_goal = self.q.copy() + self.contact_q = self.q.copy() + self.debug = {} + + @staticmethod + def _red_mask(im): + a = im.astype(np.int16) + r, g, b = a[:, :, 0], a[:, :, 1], a[:, :, 2] + return ((r > 45) & (r > 1.3 * g) & (r > 1.3 * b)).astype(np.uint8) + + def _sphere(self, im): + """Measure the visible sphere, fitting only its unoccluded outer arc.""" + mask = self._red_mask(im) + n, labels, stats, _ = cv2.connectedComponentsWithStats(mask, 8) + if n <= 1: + return None + i = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + if stats[i, cv2.CC_STAT_AREA] < 3: + return None + component = labels == i + ys, xs = np.nonzero(component) + centroid = np.array([xs.mean(), ys.mean()]) + area = float(len(xs)) + + a = im.astype(np.int16) + r, g, b = a[:, :, 0], a[:, :, 1], a[:, :, 2] + blue = (b > 65) & (b > r + 25) & (g > r + 15) + arc = np.zeros_like(component) + for dy, dx in ((1, 0), (-1, 0), (0, 1), (0, -1)): + shifted = np.zeros_like(blue) + y0, y1 = max(0, dy), 84 + min(0, dy) + x0, x1 = max(0, dx), 84 + min(0, dx) + shifted[y0:y1, x0:x1] = blue[y0-dy:y1-dy, x0-dx:x1-dx] + arc |= component & shifted + ay, ax = np.nonzero(arc) + points = np.column_stack((ax, ay)).astype(float) + fit = None + if len(points) >= 5: + # Algebraic initialization, followed by a fixed-radius geometric fit. + A = np.column_stack((points, np.ones(len(points)))) + rhs = -(points * points).sum(axis=1) + try: + d, e, f = np.linalg.lstsq(A, rhs, rcond=None)[0] + center = np.array([-d / 2.0, -e / 2.0]) + radius = float(np.sqrt(max(1.0, center @ center - f))) + if np.all(np.isfinite(center)) and 2.5 < radius < 15.0: + fit = (center, radius) + except np.linalg.LinAlgError: + pass + + reference_radius = self.radius + if fit is not None and reference_radius is not None: + if not 0.72 * reference_radius < fit[1] < 1.38 * reference_radius: + fit = None + if fit is None and len(points) >= 3 and reference_radius is not None: + center = self.target.copy() if self.target is not None else centroid.copy() + for _ in range(12): + delta = center - points + distance = np.linalg.norm(delta, axis=1) + if np.any(distance < 0.2): + break + projected = points + delta * (reference_radius / distance)[:, None] + center = projected.mean(axis=0) + residual = np.abs(np.linalg.norm(points - center, axis=1) - reference_radius) + if np.median(residual) < 1.25: + fit = (center, reference_radius) + return centroid, area, (int(xs.min()), int(xs.max()), int(ys.min()), int(ys.max())), fit, len(points) + + @staticmethod + def _hand_point(im): + """The far end of the left white-arm component is a stable wrist marker.""" + a = im.astype(np.int16) + white = ((a.min(axis=2) > 105) & + ((a.max(axis=2) - a.min(axis=2)) < 75)).astype(np.uint8) + n, labels, stats, centers = cv2.connectedComponentsWithStats(white, 8) + candidates = [i for i in range(1, n) + if stats[i, cv2.CC_STAT_AREA] > 100 and centers[i, 0] < 60] + if not candidates: + return None + i = max(candidates, key=lambda j: stats[j, cv2.CC_STAT_AREA]) + ys, xs = np.nonzero(labels == i) + points = np.column_stack((xs, ys)).astype(np.int32) + hull = cv2.convexHull(points).reshape(-1, 2) + distance = ((hull - np.array([4.0, 82.0])) ** 2).sum(axis=1) + return hull[int(np.argmax(distance))].astype(float) + + def _update_vision(self, im): + measurement = self._sphere(im) + hand = self._hand_point(im) + if hand is not None: + self.hand = hand if self.hand is None else 0.65 * self.hand + 0.35 * hand + reliable = False + if measurement is not None: + centroid, area, box, fit, arc_count = measurement + self.full_visible = box[2] > 1 and box[3] < 82 + candidate = None + measured_radius = None + if fit is not None: + center, measured_radius = fit + if self.target is None or np.linalg.norm(center - self.target) < 7.0: + candidate = center + if candidate is None and self.radius is not None: + # A mostly unoccluded disk still has a useful centroid. + if area > 0.72 * np.pi * self.radius * self.radius: + if self.target is None or np.linalg.norm(centroid - self.target) < 6.0: + candidate = centroid + measured_radius = np.sqrt(area / np.pi) + elif candidate is None and self.target is None: + candidate = centroid + measured_radius = np.sqrt(area / np.pi) + if candidate is not None: + reliable = True + if (self.target is None or self.radius is None) and candidate[0] > 46.0: + self.center_required = True + self.target = candidate if self.target is None else 0.6 * self.target + 0.4 * candidate + if measured_radius is not None and 2.5 < measured_radius < 15.0: + self.radius = (measured_radius if self.radius is None else + 0.8 * self.radius + 0.2 * measured_radius) + self.debug.update(target=self.target, hand=self.hand, radius=self.radius, + reliable=reliable, measurement=measurement) + return reliable + + def _start_search(self, t): + self.stage = "search" + self.stage_t = t + self.search_from = self.q.copy() + dyaw, elbow, roll, pitch, _, _ = self.SEARCH[self.search_index] + self.search_goal = self.contact_q.copy() + self.search_goal[2] += dyaw + self.search_goal[0] = np.clip(self.search_goal[0] + pitch, -1.6, -0.3) + self.search_goal[3] = np.clip(self.search_goal[3] + elbow, -0.10, 1.55) + self.search_goal[4] = roll + + def act(self, obs, tools): + raw = self.hold.copy() + t = int(obs["t"]) + if t < 70: + u = np.clip(t / 70.0, 0.0, 1.0) + u = u * u * (3.0 - 2.0 * u) + self.q = self.hold[4:11] + u * (self.prepose - self.hold[4:11]) + if t % 2 == 0: + self._update_vision(tools.image("head")) + else: + if self.stage == "raise": + self.stage = "approach" + reliable = True + if t % 2 == 0: + reliable = self._update_vision(tools.image("head")) + + near = False + if self.hand is not None and self.target is not None: + # The white wrist marker sits just right/below the contact point. + error = self.hand - (self.target + np.array([3.0, 2.0])) + self.error_filtered = (error if self.error_filtered is None else + 0.65 * self.error_filtered + 0.35 * error) + error = self.error_filtered + near = bool(self.radius is not None and self.radius >= 7.05 and + self.full_visible and + (not self.center_required or abs(self.target[0] - 42.0) < 4.0) and + abs(error[0]) < 4.5 and abs(error[1]) < 5.5) + self.debug["error"] = error + if self.stage in ("approach", "realign"): + ex = error[0] if abs(error[0]) > 1.5 else 0.0 + ey = error[1] if abs(error[1]) > 1.5 else 0.0 + # Coupled image Jacobian: yaw also compensates elbow's x motion. + self.q[2] += np.clip(0.0012 * ex, -0.010, 0.010) + self.q[3] -= np.clip(0.0008 * ey, -0.008, 0.008) + self.q[2] = np.clip(self.q[2], -1.80, 1.0) + self.q[3] = np.clip(self.q[3], -0.10, 1.75) + + if self.stage in ("approach", "realign"): + if (self.center_required and reliable and self.target is not None and not near + and abs(self.target[0] - 42.0) > 3.0): + raw[3] = np.clip(0.020 * (42.0 - self.target[0]), -0.25, 0.25) + if self.stage == "approach" and self.radius is None: + raw[0] = 0.08 if t < 260 else 0.0 + elif self.stage == "approach" and (self.radius < 7.35 or not self.full_visible): + raw[0] = 0.10 if reliable else 0.0 + elif self.stage == "realign" and self.radius is not None and self.radius < 6.9: + raw[0] = 0.055 if reliable else 0.0 + if near and t > 100: + self.stage = "roll" + self.stage_t = t + self.locked_q = self.q.copy() + elif self.stage == "roll": + self.q = self.locked_q.copy() + self.q[4] = 0.4 + if t - self.stage_t >= 75: + self.contact_q = self.locked_q.copy() + self.search_index = 0 + self._start_search(t) + elif self.stage == "search": + dt = t - self.stage_t + u = np.clip(dt / 15.0, 0.0, 1.0) + u = u * u * (3.0 - 2.0 * u) + self.q = self.search_from + u * (self.search_goal - self.search_from) + forward = self.SEARCH[self.search_index][5] + if 15 <= dt < 15 + abs(forward): + raw[0] = 0.10 if forward > 0 else -0.06 + raw[18] = self.SEARCH[self.search_index][4] + duration = 90 if forward else 70 + if dt >= duration: + self.search_index += 1 + if self.search_index < len(self.SEARCH): + self._start_search(t) + else: + self.stage = "realign" + self.stage_t = t + self.debug["stage"] = self.stage + self.debug["search_index"] = self.search_index + raw[4:11] = self.q + self.debug["q"] = self.q.copy() + self.debug["vx"] = raw[0] + return raw diff --git a/policies/reach_target_single/opus-s1/episodes.csv b/policies/reach_target_single/opus-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..bb0861de33bf5bf07439c8ef5113396c4fbdc924 --- /dev/null +++ b/policies/reach_target_single/opus-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,275,success,0 +620001,1,289,success,0 +620002,1,291,success,0 +620003,1,285,success,0 +620004,1,262,success,0 +620005,1,281,success,0 +620006,1,251,success,0 +620007,1,281,success,0 +620008,1,250,success,0 +620009,1,292,success,0 +620010,1,271,success,0 +620011,1,280,success,0 +620012,1,265,success,0 +620013,1,240,success,0 +620014,1,275,success,0 +620015,1,285,success,0 +620016,1,275,success,0 +620017,1,250,success,0 +620018,1,285,success,0 +620019,1,260,success,0 +620020,1,272,success,0 +620021,1,279,success,0 +620022,1,271,success,0 +620023,1,260,success,0 +620024,1,285,success,0 +620025,1,256,success,0 +620026,1,294,success,0 +620027,1,297,success,0 +620028,1,264,success,0 +620029,1,250,success,0 +620030,1,251,success,0 +620031,1,262,success,0 +620032,1,295,success,0 +620033,1,285,success,0 +620034,1,285,success,0 +620035,1,285,success,0 +620036,1,251,success,0 +620037,1,286,success,0 +620038,1,280,success,0 +620039,1,282,success,0 +620040,1,280,success,0 +620041,1,276,success,0 +620042,1,264,success,0 +620043,1,295,success,0 +620044,1,281,success,0 +620045,1,280,success,0 +620046,1,277,success,0 +620047,1,237,success,0 +620048,1,286,success,0 +620049,1,275,success,0 +620050,1,281,success,0 +620051,1,269,success,0 +620052,1,295,success,0 +620053,1,255,success,0 +620054,1,265,success,0 +620055,1,270,success,0 +620056,1,287,success,0 +620057,1,275,success,0 +620058,1,261,success,0 +620059,1,274,success,0 +620060,1,280,success,0 +620061,1,271,success,0 +620062,1,270,success,0 +620063,1,289,success,0 +620064,1,265,success,0 +620065,1,255,success,0 +620066,1,296,success,0 +620067,1,271,success,0 +620068,1,281,success,0 +620069,1,291,success,0 +620070,1,290,success,0 +620071,1,292,success,0 +620072,1,277,success,0 +620073,1,276,success,0 +620074,1,291,success,0 +620075,1,295,success,0 +620076,1,300,success,0 +620077,1,291,success,0 +620078,1,287,success,0 +620079,1,275,success,0 +620080,1,281,success,0 +620081,1,295,success,0 +620082,1,275,success,0 +620083,1,271,success,0 +620084,1,252,success,0 +620085,1,296,success,0 +620086,1,265,success,0 +620087,1,300,success,0 +620088,1,295,success,0 +620089,1,264,success,0 +620090,1,289,success,0 +620091,1,285,success,0 +620092,1,280,success,0 +620093,1,272,success,0 +620094,1,266,success,0 +620095,1,262,success,0 +620096,1,251,success,0 +620097,1,274,success,0 +620098,1,295,success,0 +620099,1,291,success,0 diff --git a/policies/reach_target_single/opus-s1/policy.py b/policies/reach_target_single/opus-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..8da1a6c484a68849499d7e04ebc330ff8e17e9db --- /dev/null +++ b/policies/reach_target_single/opus-s1/policy.py @@ -0,0 +1,313 @@ +"""Touch the red sphere with the left hand. + +Pipeline (all hand-written geometry, no learned parts): + 1. Stand still for a few steps and locate the sphere with the head camera + (red blob -> circle -> pelvis-frame position from the known sphere radius + and the head camera model calibrated against the floor checkerboard). + 2. Walk (closed loop on the pelvis pose) so the sphere sits at a fixed + comfortable offset in front of the left shoulder, raising the arm meanwhile. + 3. Solve inverse kinematics of the left arm (G1 URDF chain) for a fingertip + target on the near surface of the sphere and move there smoothly. + 4. Keep pressing; if the sphere does not light up, push a little further. +""" + +import cv2 # noqa: F401 +import numpy as np +from scipy import ndimage +from scipy.optimize import least_squares + +# ---------------------------------------------------------------- camera model +F, TH, CAMX, CAMZ = 71.96, 1.0916, 0.14, 0.417 # head camera in pelvis frame +C0 = 41.5 +RS = 0.05 # sphere radius (m), effective size of the red-mask silhouette + + +def ray(u, v): + xc = (u - C0) / F + yc = (v - C0) / F + c, s = np.cos(TH), np.sin(TH) + d = np.array([c - s * yc, -xc, -s - c * yc]) + return d / np.linalg.norm(d) + + +def sphere_rel(u, v, r): + d = ray(u, v) + dist = RS / np.sin(np.arctan(r / F)) + return np.array([CAMX, 0.0, CAMZ]) + d * dist + + +def red_mask(im): + im = im.astype(np.int32) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + return (r > 25) & (3 * g < r) & (3 * b < r) + + +def detect_sphere(im): + """(u, v, radius_px, area, clipped, brightness) of the largest red blob, or None.""" + m = red_mask(im) + 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] < 4: + return None + mm = lab == k + ys, xs = np.nonzero(mm) + area = len(xs) + H, W = mm.shape + u, v = xs.mean(), ys.mean() + rad = np.sqrt(area / np.pi) + # Boundary pixels are true silhouette points unless they lie next to the + # image border or to the (grey/white) robot, which may hide the sphere. + f = im.astype(np.int32) + mx = f.max(2) + grey = (mx - f.min(2) < 45) & ((mx > 140) | (mx < 45)) & ~ndimage.binary_dilation(mm) + near_grey = ndimage.binary_dilation(grey, iterations=2) + edge = mm & ~ndimage.binary_erosion(mm, border_value=1) + good = edge & ~near_grey + good[:2, :] = good[-2:, :] = good[:, :2] = good[:, -2:] = False + n_edge, n_good = int(edge.sum()), int(good.sum()) + clipped = n_good < 0.85 * n_edge + if clipped and n_good >= 8: + by, bx = np.nonzero(good) + bx, by = bx.astype(float), by.astype(float) + A = np.stack([bx, by, np.ones_like(bx)], 1) + sol = np.linalg.lstsq(A, bx ** 2 + by ** 2, rcond=None)[0] + u, v = sol[0] / 2, sol[1] / 2 + rad = np.sqrt(max(sol[2] + u * u + v * v, 0.0)) + 0.43 + bright = float(im[mm][:, 0].mean()) + return u, v, rad, area, clipped, bright + + +# ---------------------------------------------------------------- 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]]) + + +TIP = 0.18 # wrist-yaw joint -> fingertips + + +def fk_left(q, tip=TIP): + p = np.array([0.0, 0.10022, 0.30178]) + R = Rx(0.27931) @ 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.1, 0.00188791, -0.01]) + 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([tip, 0, 0]), R + + + +# Joint box used by the IK. The left shoulder roll cannot go below ~0 (the arm +# hits the torso), so it is bounded away from it. +LO = np.array([-2.5, 0.05, -1.0, -1.0, -1.2, -1.2, -1.2]) +HI = np.array([0.5, 1.2, 1.0, 1.4, 1.2, 1.2, 1.2]) +NOM = np.array([-0.6, 0.15, 0.0, 0.3, 0.0, 0.0, 0.0]) +SHOULDER = np.array([0.0, 0.14, 0.30]) + + +def ik(c, pen, q0=None, wdir=0.2, wreg=0.08): + """Arm angles putting the fingertips `pen` m inside the sphere centred at c, + approaching along the shoulder->sphere line.""" + d = c - SHOULDER + d = d / np.linalg.norm(d) + target = c - (RS - pen) * d + + def res(q): + tp, R = fk_left(q) + return np.concatenate([(tp - target) * 10, (R[:, 0] - d) * wdir, (q - NOM) * wreg]) + + q0 = NOM if q0 is None else q0 + s = least_squares(res, np.clip(q0, LO + 1e-3, HI - 1e-3), bounds=(LO, HI)) + return s.x + + +# ---------------------------------------------------------------- policy +STAND = np.array([0.42, 0.08]) # desired sphere position relative to pelvis (x, y) +H_STAND = 0.74 # normal pelvis height command +H_MIN = 0.64 # lowest squat used for low spheres +DZ_SHOULDER = -0.18 # desired sphere height relative to the shoulder +SQUAT_DZ = 0.4 # apparent target rise per metre of squat +PRE = -0.06 # IK pre-position: fingertips this far short of the sphere surface +PEN_MAX = 0.10 # deepest the servo pushes the fingertips past the surface +DEEPER = 0.025 # extra advance after the sphere first lights up +KI = 0.05 # integral gain on arm joint tracking error +WRIST_UV = np.array([41.0, 38.0]) # wrist-camera pixel the sphere is centred on +GAIN_UV = 0.0012 # m of target shift per pixel of wrist-camera error (every 5 steps) + + +def bright_red(im): + f = im.astype(np.int32) + return int(((f[..., 0] > 200) & (f[..., 1] < 60) & (f[..., 2] < 60)).sum()) + + +class Policy: + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.t = 0 + self.phase = "look" + self.t_phase = 0 + self.est = [] + self.sw = None # sphere centre, world frame + self.yaw0 = float(obs["low_dim_obs"][21]) + self.q_cmd = np.array(obs["low_dim_obs"][0:7], dtype=float) + self.q_sol = None + self.q_bias = np.zeros(7) + self.pen = PRE + self.height = H_STAND + self.h_goal = H_STAND + self.lit_count = 0 + self.was_lit = 0 + self.pen_lit = None + self.n_max = 0 + self.log = [] + + @staticmethod + def _pel(obs): + o = obs["low_dim_obs"] + return np.array([o[18], o[19], o[20]], dtype=float), float(o[21]) + + @staticmethod + def _to_world(rel, pel, yaw): + c, s = np.cos(yaw), np.sin(yaw) + return np.array([pel[0] + c * rel[0] - s * rel[1], pel[1] + s * rel[0] + c * rel[1], pel[2] + rel[2]]) + + @staticmethod + def _to_rel(w, pel, yaw): + c, s = np.cos(yaw), np.sin(yaw) + d = w - pel + return np.array([c * d[0] + s * d[1], -s * d[0] + c * d[1], d[2]]) + + @staticmethod + def _rot_world(v, yaw): + c, s = np.cos(yaw), np.sin(yaw) + return np.array([c * v[0] - s * v[1], s * v[0] + c * v[1], v[2]]) + + def _goto(self, phase): + self.phase = phase + self.t_phase = 0 + + def act(self, obs, tools): + pel, yaw = self._pel(obs) + raw = self.hold.copy() + self.t += 1 + self.t_phase += 1 + head = tools.image("head") + det = detect_sphere(head) + wrist = tools.image("left_wrist") if self.phase in ("reach", "servo") else None + lit = bright_red(head) >= 4 or (wrist is not None and bright_red(wrist) >= 20) + self.lit_count = self.lit_count + 1 if lit else 0 + if lit: + self.was_lit = self.t + rate = 0.0 # max arm joint change per step (rad) + + if self.phase in ("look", "walk", "settle") and det is not None and det[3] > 15: + w = self._to_world(sphere_rel(det[0], det[1], det[2]), pel, yaw) + self.est.append((self.t, self.phase, bool(det[4]), w)) + if self.phase in ("look", "walk") and self.est: + full = [e[3] for e in self.est if not e[2]] + pool = full if full else [e[3] for e in self.est] + self.sw = np.median(np.array(pool[-7:]), axis=0) + + if self.phase == "look": + if self.t >= 8 and self.sw is not None: + self._goto("walk") + elif self.phase == "walk": + rel = self._to_rel(self.sw, pel, yaw) + ex, ey = rel[0] - STAND[0], rel[1] - STAND[1] + vx = np.clip(1.2 * ex, -0.25, 0.25) + vy = np.clip(1.2 * ey, -0.25, 0.25) + sp = np.hypot(vx, vy) + if np.hypot(ex, ey) < 0.015 or self.t_phase > 300: + vx = vy = 0.0 + self._goto("settle") + elif sp < 0.07: + vx, vy = vx / sp * 0.07, vy / sp * 0.07 + raw[0], raw[1] = vx, vy + raw[3] = np.clip(-1.5 * (yaw - self.yaw0), -0.3, 0.3) + elif self.phase == "settle": + if self.t_phase >= 20: + st = [e for e in self.est if e[1] == "settle" and e[0] > self.t - 12] + full = [e[3] for e in st if not e[2]] + pool = full if full else [e[3] for e in st] + if pool: + self.sw = np.median(np.array(pool), axis=0) + # squat so the sphere sits a little below the shoulder + self.h_goal = float(np.clip(self.sw[2] - 0.30 - DZ_SHOULDER - 0.007, H_MIN, H_STAND)) + # squatting tips the torso forward, which lowers the hand + self.sw[2] += SQUAT_DZ * (H_STAND - self.h_goal) + self._goto("reach") + elif self.phase == "reach": + rate = 0.03 + if self.t_phase > 40 and np.max(np.abs(self.q_sol - self.q_cmd)) < 0.02: + self._goto("servo") + elif self.phase == "servo": + rate = 0.02 + + # pelvis height: move smoothly towards the goal + self.height += np.clip(self.h_goal - self.height, -0.003, 0.003) + raw[2] = self.height + + if self.phase in ("reach", "servo"): + if self.phase == "servo" and self.t % 5 == 0: + if self.was_lit: + # touching: go a little deeper so the contact is not marginal, then hold + if self.pen_lit is None: + self.pen_lit = self.pen + self.pen = min(self.pen + 0.004, self.pen_lit + DEEPER, PEN_MAX) + elif wrist is not None: + self._servo(wrist, yaw) + if self.pen >= PEN_MAX: + self.n_max += 1 + if self.n_max > 10: # pushed through without touching: retry + self.pen = PRE + self.n_max = 0 + if self.t % 5 == 0 or self.q_sol is None: + rel = self._to_rel(self.sw, pel, yaw) + self.q_sol = ik(rel, self.pen, q0=self.q_sol) + self.q_cmd = self.q_cmd + np.clip(self.q_sol - self.q_cmd, -rate, rate) + # integral action against the steady sag of the position servos + q_act = np.asarray(obs["low_dim_obs"][0:7], dtype=float) + self.q_bias = np.clip(self.q_bias + KI * (self.q_cmd - q_act), -0.25, 0.25) + raw[4:11] = self.q_cmd + self.q_bias + self.log.append((self.t, self.phase, pel.copy(), yaw, None if det is None else det[:3], lit, self.pen)) + return raw + + def _servo(self, wrist, yaw): + """Centre the sphere in the wrist camera, then advance along the approach.""" + m = red_mask(wrist) + frac = m.mean() + _, R = fk_left(self.q_sol) + if frac > 0.002: + ys, xs = np.nonzero(m) + e = np.array([xs.mean(), ys.mean()]) - WRIST_UV + if frac > 0.9: + e = e * 0.0 + # image right = hand -y, image down = hand -z + shift = GAIN_UV * (e[0] * -R[:, 1] + e[1] * -R[:, 2]) + self.sw = self.sw + self._rot_world(shift, yaw) + if np.hypot(*e) < 10 or frac > 0.5: + self.pen = min(self.pen + 0.006, PEN_MAX) + else: + # nothing in view: either inside the sphere or far off; creep forward + self.pen = min(self.pen + 0.004, PEN_MAX) diff --git a/policies/reach_target_single/opus-s2/episodes.csv b/policies/reach_target_single/opus-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..2cc7b38525f55315c4296eee73d6954c2174bc49 --- /dev/null +++ b/policies/reach_target_single/opus-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,232,success,0 +620001,1,247,success,0 +620002,1,306,success,0 +620003,1,224,success,0 +620004,1,246,success,0 +620005,1,268,success,0 +620006,1,267,success,0 +620007,1,281,success,0 +620008,1,256,success,0 +620009,1,243,success,0 +620010,1,247,success,0 +620011,1,232,success,0 +620012,1,258,success,0 +620013,1,260,success,0 +620014,1,216,success,0 +620015,1,221,success,0 +620016,1,212,success,0 +620017,1,232,success,0 +620018,1,285,success,0 +620019,1,272,success,0 +620020,1,276,success,0 +620021,1,206,success,0 +620022,1,270,success,0 +620023,1,213,success,0 +620024,1,290,success,0 +620025,1,213,success,0 +620026,1,237,success,0 +620027,1,250,success,0 +620028,1,242,success,0 +620029,1,231,success,0 +620030,0,900,timeout,0 +620031,1,214,success,0 +620032,1,248,success,0 +620033,1,242,success,0 +620034,1,223,success,0 +620035,1,274,success,0 +620036,1,264,success,0 +620037,1,241,success,0 +620038,1,292,success,0 +620039,1,230,success,0 +620040,1,224,success,0 +620041,1,238,success,0 +620042,1,251,success,0 +620043,1,244,success,0 +620044,1,287,success,0 +620045,1,195,success,0 +620046,1,195,success,0 +620047,1,226,success,0 +620048,1,219,success,0 +620049,1,228,success,0 +620050,1,225,success,0 +620051,1,226,success,0 +620052,1,293,success,0 +620053,1,266,success,0 +620054,1,224,success,0 +620055,1,268,success,0 +620056,1,226,success,0 +620057,1,264,success,0 +620058,1,269,success,0 +620059,1,279,success,0 +620060,1,273,success,0 +620061,1,279,success,0 +620062,1,222,success,0 +620063,1,244,success,0 +620064,1,275,success,0 +620065,1,271,success,0 +620066,1,250,success,0 +620067,1,278,success,0 +620068,1,221,success,0 +620069,1,240,success,0 +620070,1,249,success,0 +620071,1,247,success,0 +620072,1,224,success,0 +620073,1,270,success,0 +620074,1,247,success,0 +620075,1,252,success,0 +620076,1,249,success,0 +620077,1,244,success,0 +620078,1,245,success,0 +620079,1,277,success,0 +620080,1,235,success,0 +620081,1,244,success,0 +620082,1,224,success,0 +620083,1,267,success,0 +620084,1,258,success,0 +620085,1,250,success,0 +620086,1,223,success,0 +620087,1,242,success,0 +620088,1,239,success,0 +620089,1,223,success,0 +620090,1,239,success,0 +620091,1,228,success,0 +620092,1,273,success,0 +620093,1,281,success,0 +620094,1,261,success,0 +620095,1,242,success,0 +620096,1,213,success,0 +620097,1,228,success,0 +620098,1,286,success,0 +620099,1,239,success,0 diff --git a/policies/reach_target_single/opus-s2/policy.py b/policies/reach_target_single/opus-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..4a834c130fc4953fa8800db68b6d1334f667c336 --- /dev/null +++ b/policies/reach_target_single/opus-s2/policy.py @@ -0,0 +1,282 @@ +"""Touch the red sphere with the left hand (Unitree G1). + +Pipeline + 1. Locate the sphere from the head camera: red blob centroid + apparent diameter + through a pinhole model of the head camera (pose / focal length calibrated by + hand against the robot's own arm and a sphere seen from several base poses). + 2. Walk straight forward until the sphere is a fixed distance ahead of the pelvis. + 3. Re-locate the sphere, solve the left-arm inverse kinematics (analytic forward + kinematics of the G1 arm, numeric least squares) for the finger tips to reach + the sphere centre, and move the arm there smoothly. + 4. Hold once the sphere lights up (touched); small corrective pushes otherwise. +""" + +import cv2 # noqa: F401 +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) + + +_AX = {"x": _rx, "y": _ry, "z": _rz} +_TORSO = np.array([-0.0039635, 0.0, 0.054]) +# G1 left arm joint frames (parent offset, fixed rotation, axis) +_LEFT = [ + (np.array([0.0039563, 0.10022, 0.24778]), _rpy(0.27931, 5.4949e-05, -0.00019159), "y"), + (np.array([0.0, 0.038, -0.013831]), _rpy(-0.27925, 0, 0), "x"), + (np.array([0.0, 0.00624, -0.1032]), np.eye(3), "z"), + (np.array([0.015783, 0.0, -0.080518]), np.eye(3), "y"), + (np.array([0.100, 0.00188791, -0.010]), np.eye(3), "x"), + (np.array([0.038, 0.0, 0.0]), np.eye(3), "y"), + (np.array([0.046, 0.0, 0.0]), np.eye(3), "z"), +] +TIP = 0.18 # finger tips beyond the wrist-yaw joint + + +def fk_left(q, tip=TIP): + """Finger-tip position and hand rotation of the left arm, pelvis frame.""" + p = _TORSO.copy() + rot = np.eye(3) + for (off, r0, ax), qi in zip(_LEFT, q): + p = p + rot @ off + rot = rot @ r0 @ _AX[ax](qi) + return p + rot @ np.array([tip, 0.0, 0.0]), rot + + +# ---------------------------------------------------------------- head camera +CAM_POS = np.array([0.1511, 0.0021, 0.3941]) +CAM_ROT = _rz(-0.0232) @ _ry(1.0814) @ _rx(-0.0343) +CAM_F = 65.59 +CAM_C = 41.5 +SPHERE_R = 0.0434 + + +def red_mask(im): + im = im.astype(np.int32) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + return (r > 60) & (r > 2 * g + 20) & (r > 2 * b + 20) + + +def detect(im): + """Largest red blob: dict(u, v, diam, clipped, n, bright) or None.""" + m = red_mask(im).astype(np.uint8) + n, lab, stats, cents = cv2.connectedComponentsWithStats(m, connectivity=8) + if n <= 1: + return None + k = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + x, y, w, h, area = stats[k] + if area < 6: + return None + clipped = x <= 0 or y <= 0 or x + w >= im.shape[1] or y + h >= im.shape[0] + bright = int(((im[..., 0] > 200) & (m > 0)).sum()) + return dict(u=float(cents[k][0]), v=float(cents[k][1]), + diam=2.0 * np.sqrt(area / np.pi), w=int(w), h=int(h), + clipped=bool(clipped), n=int(area), bright=bright) + + +def locate(det): + """Sphere centre in the pelvis frame from a head-camera detection.""" + depth = 2 * CAM_F * SPHERE_R / det["diam"] + dc = np.array([1.0, -(det["u"] - CAM_C) / CAM_F, -(det["v"] - CAM_C) / CAM_F]) * depth + return CAM_POS + CAM_ROT @ dc + + +def touched(tools): + """The sphere turns bright red while it is touched.""" + for cam in ("head", "left_wrist"): + im = tools.image(cam) + m = red_mask(im) + if ((im[..., 0] > 200) & (im[..., 1] < 70) & m).sum() >= 12: + return True + return False + + +# ---------------------------------------------------------------- IK +Q_LO = np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.9722, -1.6144, -1.6144]) +Q_HI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.9722, 1.6144, 1.6144]) +Q_NOM = np.array([-0.8, 0.2, 0.0, 0.6, 0.0, 0.0, 0.0]) + + +def ik_left(target, q0=None): + """Shoulder (3) + elbow angles putting the finger tips at ``target``.""" + q0 = Q_NOM[:4] if q0 is None else q0[:4] + + def res(x): + q = np.concatenate([x, [0.0, 0.0, 0.0]]) + tip, _ = fk_left(q) + return np.concatenate([(tip - target) * 10.0, 0.05 * (x - Q_NOM[:4])]) + + lo = Q_LO[:4] + 0.05 + hi = Q_HI[:4] - 0.05 + lo[1] = -0.2 # do not cross into the torso + sol = least_squares(res, np.clip(q0, lo, hi), bounds=(lo, hi)) + q = np.concatenate([sol.x, [0.0, 0.0, 0.0]]) + err = np.linalg.norm(fk_left(q)[0] - target) + return q, err + + +# ---------------------------------------------------------------- policy +STAND_X = 0.40 # wanted sphere distance ahead of the pelvis before reaching +WRIST_U, WRIST_V = 44.0, 40.0 # left-wrist pixel the finger tips point at +SERVO_K = 0.004 # m per step per unit normalised pixel error +SERVO_MAX = 0.10 # max servo drift from the estimated sphere centre, m +LAT_MIN, LAT_MAX = 0.0, 0.16 # wanted lateral sphere offset (pelvis frame), m +PUSH = 0.0015 # m per step along the hand axis while not touching + + +class Policy: + """Locate, approach, reach, hold.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = "look" + self.t_phase = 0 + self.obs_buf = [] + self.goal_world = None + self.arm_q = np.zeros(7) + self.arm_from = None + self.arm_to = None + self.touch_count = 0 + self.log = [] + + def _set_phase(self, p): + self.phase = p + self.t_phase = 0 + + def _pelvis(self, obs): + lo = obs["low_dim_obs"] + return lo[18], lo[19], lo[21] + + def act(self, obs, tools): + raw = self.hold.copy() + lo = obs["low_dim_obs"] + px, py, yaw = self._pelvis(obs) + self.t_phase += 1 + raw[4:11] = self.arm_q + + if self.phase == "look": + det = detect(tools.image("head")) + if det is not None and not det["clipped"]: + self.obs_buf.append(locate(det)) + if self.t_phase >= 10: + if self.obs_buf: + p = np.median(np.array(self.obs_buf), axis=0) + c, s = np.cos(yaw), np.sin(yaw) + self.goal_world = np.array([px + c * p[0] - s * p[1], py + s * p[0] + c * p[1]]) + self.obs_buf = [] + self._set_phase("walk") + else: + # sphere not (fully) visible: creep forward and look again + raw[0] = 0.12 + if self.t_phase > 60: + self.t_phase = 0 + + elif self.phase == "walk": + # refine the goal whenever the sphere is fully visible + det = detect(tools.image("head")) + if det is not None and not det["clipped"]: + p = locate(det) + c, s = np.cos(yaw), np.sin(yaw) + g = np.array([px + c * p[0] - s * p[1], py + s * p[0] + c * p[1]]) + self.goal_world = 0.9 * self.goal_world + 0.1 * g + c, s = np.cos(yaw), np.sin(yaw) + d = self.goal_world - np.array([px, py]) + fwd = c * d[0] + s * d[1] + lat = -s * d[0] + c * d[1] + err = fwd - STAND_X + lat_err = 0.0 + if lat < LAT_MIN: + lat_err = lat - LAT_MIN - 0.02 + elif lat > LAT_MAX: + lat_err = lat - LAT_MAX + 0.02 + moving = False + if err > 0.02: + raw[0] = float(np.clip(0.8 * err, 0.07, 0.25)) + moving = True + if abs(lat_err) > 0.015: + raw[1] = float(np.sign(lat_err) * np.clip(0.8 * abs(lat_err), 0.07, 0.2)) + moving = True + if not moving or self.t_phase >= 400: + self._set_phase("settle") + + elif self.phase == "settle": + det = detect(tools.image("head")) + if self.t_phase > 25 and det is not None and not det["clipped"]: + self.obs_buf.append(locate(det)) + if self.t_phase >= 40: + if self.obs_buf: + p = np.median(np.array(self.obs_buf), axis=0) + else: + c, s = np.cos(yaw), np.sin(yaw) + d = self.goal_world - np.array([px, py]) + p = np.array([c * d[0] + s * d[1], -s * d[0] + c * d[1], 0.2]) + self.target = p + q, err = ik_left(p) + self.ik_err = err + self.arm_from = np.asarray(lo[0:7], dtype=float).copy() + self.arm_from[4:] = 0.0 + self.arm_to = q + self._set_phase("reach") + + elif self.phase == "reach": + T = 60 + a = min(1.0, self.t_phase / T) + a = 0.5 - 0.5 * np.cos(np.pi * a) + # lift the hand first (elbow bent) then extend + self.arm_q = (1 - a) * self.arm_from + a * self.arm_to + raw[4:11] = self.arm_q + if self.t_phase >= T: + self.tgt = self.target.copy() + self._set_phase("servo") + + elif self.phase == "servo": + if touched(tools): + self.touch_count += 1 + else: + self.touch_count = 0 + if self.touch_count >= 3: + self._set_phase("hold") + elif self.t_phase > 15: + det = detect(tools.image("left_wrist")) + _, rot = fk_left(np.asarray(lo[0:7], dtype=float)) + step = np.zeros(3) + if det is not None: + eu = (det["u"] - WRIST_U) / CAM_F + ev = (det["v"] - WRIST_V) / CAM_F + step += SERVO_K * (rot @ np.array([0.0, -eu, -ev])) + step += PUSH * rot[:, 0] + self.tgt = self.tgt + step + dev = self.tgt - self.target + if np.linalg.norm(dev) > SERVO_MAX: + self.tgt = self.target + dev * SERVO_MAX / np.linalg.norm(dev) + q, _ = ik_left(self.tgt, self.arm_q) + self.arm_q = q + raw[4:11] = self.arm_q + + elif self.phase == "hold": + if not touched(tools): + self.touch_count = 0 + self._set_phase("servo") + raw[4:11] = self.arm_q + + self.log.append((int(obs["t"]), self.phase)) + return raw diff --git a/policies/reach_target_single/opus-s3/episodes.csv b/policies/reach_target_single/opus-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..19787472c6adfb1ccbcfd176e5f359d732b5d7d8 --- /dev/null +++ b/policies/reach_target_single/opus-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,264,success,0 +620001,1,236,success,0 +620002,1,236,success,0 +620003,1,220,success,0 +620004,1,233,success,0 +620005,1,266,success,0 +620006,1,243,success,0 +620007,1,256,success,0 +620008,1,188,success,0 +620009,1,233,success,0 +620010,1,242,success,0 +620011,1,237,success,0 +620012,1,235,success,0 +620013,1,195,success,0 +620014,1,261,success,0 +620015,1,259,success,0 +620016,1,231,success,0 +620017,1,229,success,0 +620018,1,254,success,0 +620019,1,266,success,0 +620020,1,267,success,0 +620021,1,236,success,0 +620022,1,260,success,0 +620023,1,212,success,0 +620024,1,262,success,0 +620025,1,196,success,0 +620026,1,232,success,0 +620027,1,245,success,0 +620028,1,233,success,0 +620029,1,231,success,0 +620030,1,232,success,0 +620031,1,191,success,0 +620032,1,242,success,0 +620033,1,275,success,0 +620034,1,309,success,0 +620035,1,260,success,0 +620036,1,234,success,0 +620037,1,256,success,0 +620038,1,267,success,0 +620039,1,261,success,0 +620040,1,269,success,0 +620041,1,276,success,0 +620042,1,262,success,0 +620043,1,235,success,0 +620044,1,229,success,0 +620045,1,254,success,0 +620046,1,234,success,0 +620047,1,231,success,0 +620048,1,211,success,0 +620049,1,258,success,0 +620050,1,257,success,0 +620051,1,236,success,0 +620052,1,238,success,0 +620053,1,235,success,0 +620054,1,219,success,0 +620055,1,241,success,0 +620056,1,264,success,0 +620057,1,266,success,0 +620058,1,263,success,0 +620059,1,278,success,0 +620060,1,287,success,0 +620061,1,280,success,0 +620062,1,269,success,0 +620063,1,233,success,0 +620064,1,264,success,0 +620065,1,238,success,0 +620066,1,240,success,0 +620067,1,241,success,0 +620068,1,268,success,0 +620069,1,252,success,0 +620070,1,238,success,0 +620071,1,239,success,0 +620072,1,266,success,0 +620073,1,265,success,0 +620074,1,233,success,0 +620075,1,239,success,0 +620076,1,242,success,0 +620077,1,274,success,0 +620078,1,264,success,0 +620079,1,233,success,0 +620080,1,280,success,0 +620081,1,237,success,0 +620082,1,272,success,0 +620083,1,259,success,0 +620084,1,205,success,0 +620085,1,242,success,0 +620086,1,223,success,0 +620087,1,239,success,0 +620088,1,236,success,0 +620089,1,225,success,0 +620090,1,223,success,0 +620091,1,237,success,0 +620092,1,286,success,0 +620093,1,279,success,0 +620094,1,268,success,0 +620095,1,234,success,0 +620096,1,228,success,0 +620097,1,287,success,0 +620098,1,235,success,0 +620099,1,258,success,0 diff --git a/policies/reach_target_single/opus-s3/policy.py b/policies/reach_target_single/opus-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..f216d7227d089f78298f0586e309130b5e11eaf4 --- /dev/null +++ b/policies/reach_target_single/opus-s3/policy.py @@ -0,0 +1,304 @@ +"""Touch the red sphere with the left hand (Unitree G1). + +Hand-written pipeline: + 1. At reset, find the sphere in the head camera and back-project it to a 3-D + point (head camera pose / focal length / sphere radius were calibrated by + hand from a few development episodes against the arm kinematics below). + 2. Walk forward/sideways so the sphere sits at a comfortable stand-off from + the pelvis (the demonstration also walks in before reaching). + 3. Move the left arm with damped least-squares IK (G1 URDF kinematics) to a + pre-touch pose with the sphere straight ahead of the hand, refining the + sphere estimate from the left wrist camera, then advance until the + sphere's centre is between the fingertips. + 4. When the sphere turns bright red (it lights up while touched) hold still. +""" + +import cv2 +import numpy as np +from scipy.optimize import least_squares +from scipy.spatial.transform import Rotation + + +# ---------------------------------------------------------------- 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) + + +# Left arm of the G1 29-dof URDF: (joint origin xyz, origin rpy, joint axis). +_LEFT = [ + ((0.0039563, 0.10022, 0.24778), (0.27931, 5.4949e-05, -0.00019159), _ry), + ((0.0, 0.038, -0.013831), (-0.27925, 0, 0), _rx), + ((0.0, 0.00624, -0.1032), (0, 0, 0), _rz), + ((0.015783, 0.0, -0.080518), (0, 0, 0), _ry), + ((0.100, 0.00188791, -0.010), (0, 0, 0), _rx), + ((0.038, 0.0, 0.0), (0, 0, 0), _ry), + ((0.046, 0.0, 0.0), (0, 0, 0), _rz), +] +_LEFT_FIXED = [(np.array(xyz), _rpy(*r)) for xyz, r, _ in _LEFT] +_LEFT_AXES = [f for _, _, f in _LEFT] +TORSO_IN_PELVIS = np.array([-0.0039635, 0.0, 0.044]) +SHOULDER = np.array([0.0, 0.14, 0.30]) # rough left shoulder, pelvis frame + + +def hand_pose(q): + """Left wrist_yaw_link pose (position, rotation) in the pelvis frame.""" + p = TORSO_IN_PELVIS.copy() + R = np.eye(3) + for (xyz, R0), f, qi in zip(_LEFT_FIXED, _LEFT_AXES, q): + p = p + R @ xyz + R = R @ R0 @ f(qi) + return p, R + + +Q_LO = np.array([-3.0, 0.02, -2.5, -1.0, -1.9, -1.55, -1.55]) +Q_HI = np.array([2.6, 2.2, 2.5, 2.05, 1.9, 1.55, 1.55]) +Q_NOM = np.array([-0.5, 0.2, 0.0, 0.5, 0.0, 0.0, 0.0]) + +# ------------------------------------------------------------------- cameras +# Head camera (pelvis frame): position, pitch, focal length (px), yaw. +HEAD_POS = np.array([0.137332, 0.002874, 0.334569]) +HEAD_R = _rz(-0.0078) @ _ry(1.046243) +HEAD_F = 58.361775 +HEAD_BIAS = np.array([0.02, 0.0, 0.0]) +# Left wrist camera in the wrist_yaw_link frame. +WCAM_T = np.array([0.106539, -0.01377, 0.047566]) +WCAM_R = Rotation.from_rotvec([0.077561, 0.687725, 0.028567]).as_matrix() +WCAM_F = 74.170081 +SPHERE_R = 0.046763 +CX = CY = 41.5 + +# Where the sphere centre should end up, in the wrist_yaw_link frame. +T_TOUCH = np.array([0.135, 0.01, 0.01]) +# Look pose: sphere on the wrist camera's optical axis, LOOK_D ahead of it. +LOOK_D = 0.18 +T_PRE = WCAM_T + WCAM_R @ np.array([LOOK_D, 0.0, 0.0]) +STANDOFF_XS = np.arange(0.24, 0.44, 0.02) # candidate sphere x ahead of the pelvis +STANDOFF_Y = 0.06 # desired sphere y (left) of the pelvis after walking + + +def red_blob(im): + """Largest red blob in an RGB image: dict or None.""" + r = im[..., 0].astype(np.int16) + g = im[..., 1].astype(np.int16) + b = im[..., 2].astype(np.int16) + m = ((r > 25) & (r > 2 * g + 12) & (r > 2 * b + 12)).astype(np.uint8) + n, lab, st, cen = cv2.connectedComponentsWithStats(m, connectivity=8) + if n <= 1: + return None + k = 1 + int(np.argmax(st[1:, cv2.CC_STAT_AREA])) + area = int(st[k, cv2.CC_STAT_AREA]) + if area < 4: + return None + x, y, w, h = st[k, :4] + H, W = m.shape + border = x <= 0 or y <= 0 or x + w >= W or y + h >= H + cnts, _ = cv2.findContours((lab == k).astype(np.uint8), cv2.RETR_EXTERNAL, + cv2.CHAIN_APPROX_NONE) + (cu, cv), rad = cv2.minEnclosingCircle(cnts[0]) + pix = im[lab == k] + return dict(u=float(cu), v=float(cv), r=float(rad), area=area, + border=bool(border), bright=float(pix[:, 0].mean()), + frac=area / float(H * W)) + + +def pel_to_world(p, pel): + c, s = np.cos(pel[3]), np.sin(pel[3]) + return np.array([pel[0] + c * p[0] - s * p[1], pel[1] + s * p[0] + c * p[1], pel[2] + p[2]]) + + +def world_to_pel(p, pel): + c, s = np.cos(pel[3]), np.sin(pel[3]) + dx, dy = p[0] - pel[0], p[1] - pel[1] + return np.array([c * dx + s * dy, -s * dx + c * dy, p[2] - pel[2]]) + + +def ray_point(u, v, depth, f): + """Camera-frame point (x forward, y left, z up) for a pixel and axial depth.""" + return np.array([depth, -depth * (u - CX) / f, -depth * (v - CY) / f]) + + +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.t = 0 + self.phase = "init" + self.S = None # sphere centre, world frame + self.S_head = None + self.wrist_est = [] + self.q_cmd = np.asarray(obs["low_dim_obs"][0:7], dtype=np.float64).copy() + self.q_ik = Q_NOM.copy() + self.alpha = 0.0 # 0 = pre-touch, 1 = touch target + self.phase_t = 0 + self.bright_count = 0 + self.dark_count = 0 + self.extra = 0.0 + + # ------------------------------------------------------------ estimation + def head_estimate(self, im): + b = red_blob(im) + if b is None or b["r"] < 2: + return None + depth = HEAD_F * SPHERE_R / b["r"] + # HEAD_BIAS: mean offset of the head estimate from the wrist-camera estimate + return HEAD_POS + HEAD_R @ ray_point(b["u"], b["v"], depth, HEAD_F) + HEAD_BIAS + + def wrist_estimate(self, b, q, pel): + if b is None or b["border"] or b["r"] < 5 or b["r"] > 32 or b["frac"] < 0.004: + return None + p, R = hand_pose(q) + cam_p = p + R @ WCAM_T + cam_R = R @ WCAM_R + depth = WCAM_F * SPHERE_R / b["r"] + s_pel = cam_p + cam_R @ ray_point(b["u"], b["v"], depth, WCAM_F) + return pel_to_world(s_pel, pel) + + # -------------------------------------------------------------------- IK + def solve_ik(self, S_pel, T): + a = S_pel - SHOULDER + a[2] *= 0.3 + a /= np.linalg.norm(a) + + def res(q): + p, R = hand_pose(q) + e = (p + R @ T - S_pel) / 0.003 + o = (R[:, 0] - a) / 0.3 + return np.r_[e, o, (q - Q_NOM) * 0.05, (q - q0) * 0.3] + + q0 = np.clip(self.q_ik, Q_LO + 1e-4, Q_HI - 1e-4) + sol = least_squares(res, q0, bounds=(Q_LO, Q_HI), max_nfev=60) + self.q_ik = sol.x + p, R = hand_pose(sol.x) + return sol.x, float(np.linalg.norm(p + R @ T - S_pel)) + + def plan_standoff(self, z): + """Pick the walking stand-off whose simulated reach is smoothest.""" + best, best_x = None, 0.32 + for x in STANDOFF_XS: + S = np.array([x, STANDOFF_Y, z]) + self.q_ik = Q_NOM.copy() + for _ in range(4): + q, e = self.solve_ik(S, T_PRE) + qs, errs = [q], [e] + for al in np.linspace(0.1, 1.0, 10): + q, e = self.solve_ik(S, (1 - al) * T_PRE + al * T_TOUCH) + qs.append(q) + errs.append(e) + qs = np.array(qs) + jump = np.abs(np.diff(qs, axis=0)).sum() + near = np.sum(np.minimum(qs - Q_LO, Q_HI - qs)[:, [0, 2, 3, 4, 5, 6]] < 0.1) + straight = max(0.0, qs[:, 3].max() - 1.15) + cost = (jump + 0.3 * np.abs(qs[-1] - Q_NOM).sum() + 200 * max(errs) + 0.5 * near + + 4.0 * straight) + if best is None or cost < best: + best, best_x = cost, float(x) + self.q_ik = Q_NOM.copy() + return best_x + + # ------------------------------------------------------------------- act + def act(self, obs, tools): + lo = np.asarray(obs["low_dim_obs"], dtype=np.float64) + q = lo[0:7] + pel = lo[18:22] + raw = self.hold.copy() + self.t += 1 + self.phase_t += 1 + + if self.phase == "init": + est = self.head_estimate(tools.image("head")) + if est is not None: + self.wrist_est.append(pel_to_world(est, pel)) + if self.phase_t >= 3: + if self.wrist_est: + self.S_head = np.mean(self.wrist_est, axis=0) + else: + self.S_head = pel_to_world(np.array([0.5, 0.05, 0.08]), pel) + self.S = self.S_head.copy() + self.wrist_est = [] + self.standoff_x = self.plan_standoff(world_to_pel(self.S, pel)[2]) + self.phase, self.phase_t = "walk", 0 + + S_pel = world_to_pel(self.S, pel) if self.S is not None else None + + if self.phase == "walk": + ex = S_pel[0] - self.standoff_x + ey = S_pel[1] - STANDOFF_Y + vx = float(np.clip(1.2 * ex, -0.25, 0.25)) + vy = float(np.clip(1.2 * ey, -0.2, 0.2)) + sp = np.hypot(vx, vy) + if sp < 0.065: + if sp > 1e-6 and (abs(ex) > 0.02 or abs(ey) > 0.02): + vx, vy = vx * 0.065 / sp, vy * 0.065 / sp + else: + vx = vy = 0.0 + raw[0], raw[1] = vx, vy + if abs(ex) < 0.02 and abs(ey) < 0.02 or self.phase_t > 300: + raw[0] = raw[1] = 0.0 + self.phase, self.phase_t = "settle", 0 + # meanwhile bring the arm towards the pre-touch posture + target, _ = self.solve_ik(np.array([self.standoff_x, STANDOFF_Y, S_pel[2]]), T_PRE) + self.move_arm(target, 0.025) + elif self.phase == "settle": + target, _ = self.solve_ik(S_pel, T_PRE) + self.move_arm(target, 0.025) + if self.phase_t > 40 and np.max(np.abs(q - self.q_cmd)) < 0.05: + self.phase, self.phase_t = "look", 0 + elif self.phase in ("look", "approach", "hold"): + b = red_blob(tools.image("left_wrist")) + hb = red_blob(tools.image("head")) + lit = (b is not None and b["bright"] > 190 and b["frac"] > 0.05) or ( + hb is not None and hb["bright"] > 180 and hb["area"] >= 5) + if lit: + self.bright_count += 1 + self.dark_count = 0 + else: + self.bright_count = 0 + self.dark_count += 1 + if self.phase in ("look", "approach"): + w = self.wrist_estimate(b, q, pel) + if w is not None and np.linalg.norm(w - self.S_head) < 0.12: + self.wrist_est.append(w) + self.S = np.median(np.array(self.wrist_est[-15:]), axis=0) + S_pel = world_to_pel(self.S, pel) + if self.phase == "look": + target, _ = self.solve_ik(S_pel, T_PRE) + self.move_arm(target, 0.02) + if self.phase_t > 25: + self.phase, self.phase_t = "approach", 0 + elif self.phase == "approach": + self.alpha = min(1.0, self.alpha + 0.02) + if self.alpha >= 1.0 and self.bright_count == 0 and self.phase_t > 75: + self.extra = min(0.06, self.extra + 0.0005) + T = (1 - self.alpha) * T_PRE + self.alpha * T_TOUCH - np.array([self.extra, 0, 0]) + target, _ = self.solve_ik(S_pel, T) + self.move_arm(target, 0.02) + if self.bright_count >= 2: + # touching: freeze the arm where it is + self.q_cmd = np.clip(self.q_cmd, q - 0.03, q + 0.03) + self.phase, self.phase_t = "hold", 0 + else: # hold: keep the arm still; resume servoing if contact is lost + if self.dark_count >= 8: + self.phase, self.phase_t = "approach", 0 + + raw[4:11] = self.q_cmd + return raw + + def move_arm(self, target, step): + d = np.clip(target - self.q_cmd, -step, step) + self.q_cmd = self.q_cmd + d diff --git a/policies/sandwich_remove/astra-s1/episodes.csv b/policies/sandwich_remove/astra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..6f788ca2333c548bfed38b3191508809dc5aa764 --- /dev/null +++ b/policies/sandwich_remove/astra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,3150,timeout,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,1,1521,success,0 +620009,0,3150,timeout,0 +620010,1,1560,success,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,1,1310,success,0 +620014,0,3150,timeout,0 +620015,0,3150,timeout,0 +620016,0,3150,timeout,0 +620017,0,3150,timeout,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,1,1574,success,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,3150,timeout,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,3150,timeout,0 +620031,1,1575,success,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,1,1894,success,0 +620043,0,3150,timeout,0 +620044,0,3150,timeout,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,1,1522,success,0 +620048,0,3150,timeout,0 +620049,0,3150,timeout,0 +620050,0,3150,timeout,0 +620051,0,3150,timeout,0 +620052,1,1540,success,0 +620053,0,3150,timeout,0 +620054,0,3150,timeout,0 +620055,0,3150,timeout,0 +620056,1,1531,success,0 +620057,0,3150,timeout,0 +620058,1,1564,success,0 +620059,0,3150,timeout,0 +620060,0,3150,timeout,0 +620061,0,3150,timeout,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,1,1240,success,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,3150,timeout,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,3150,timeout,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,3150,timeout,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,1,1341,success,0 +620084,0,3150,timeout,0 +620085,0,3150,timeout,0 +620086,0,3150,timeout,0 +620087,1,1345,success,0 +620088,0,3150,timeout,0 +620089,1,1511,success,0 +620090,0,3150,timeout,0 +620091,0,3150,timeout,0 +620092,0,3150,timeout,0 +620093,0,3150,timeout,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,1,1522,success,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/astra-s1/policy.py b/policies/sandwich_remove/astra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..888ec485a26e5fb234d091a24acaedb8790f9df1 --- /dev/null +++ b/policies/sandwich_remove/astra-s1/policy.py @@ -0,0 +1,75 @@ +"""Deterministic, hand-written two-arm manipulation controller. + +Arm motions are manually tuned physical joint targets. Walking uses pelvis +position and yaw feedback. No demonstration files or learned models are used. +""" + +import numpy as np + + +class Policy: + # duration, arm/gripper targets, optional world-frame base position + PHASES = ( + (60, {5: -.65, 12: -.65, 19: 0, 20: 0}, None), + (180, {}, (.22, .25)), + # Close around the spatula handle and lift it clear of the pan. + (45, {14: .3, 18: -.3}, None), + (100, {12: -.28}, None), + (40, {20: 1}, None), + (80, {12: -.65}, None), + (65, {14: -.5, 18: 0}, None), + # Approach the pan handle horizontally with the other gripper. + (100, {5: -.2, 7: -.12, 9: 1.57}, None), + (120, {}, (.30, .25)), + (40, {19: 1}, None), + (80, {5: -.65}, None), + (440, {}, (.27, -.9)), + # Turn the pan over the board, then lift it clear. + (100, {9: -1.57}, None), + (100, {11: .7}, None), + (100, {11: 1.5, 5: -.45}, None), + (120, {}, None), + (120, {5: -.95, 7: .5}, None), + # Bring the spatula across the board and withdraw after the sweep. + (120, {12: -.5, 14: -.3, 17: .6, 18: 1.3}, None), + (100, {12: -.3, 17: .7}, None), + (120, {12: -.65, 17: 0, 18: 0}, None), + (300, {}, None), + ) + + def reset(self, obs, tools): + self.action = np.asarray(tools.hold_action(), dtype=np.float64).copy() + self.phase = 0 + self.elapsed = 0 + self.start = self.action.copy() + + def act(self, obs, tools): + q = obs['low_dim_obs'] + action = self.action.copy() + action[:2] = 0 + action[3] = 0 + duration, targets, destination = self.PHASES[self.phase] + fraction = min(1.0, (self.elapsed + 1) / min(duration, 80)) + for joint, target in targets.items(): + action[joint] = self.start[joint] + fraction * (target - self.start[joint]) + + if destination is not None: + error = np.asarray(destination) - q[21:23] + velocity = np.clip(2.0 * error, -.23, .23) + velocity[np.abs(error) < .012] = 0 + for axis in range(2): + if 0 < abs(velocity[axis]) < .065: + velocity[axis] = np.sign(velocity[axis]) * .065 + yaw = q[24] + cosine, sine = np.cos(yaw), np.sin(yaw) + action[0] = cosine * velocity[0] + sine * velocity[1] + action[1] = -sine * velocity[0] + cosine * velocity[1] + action[3] = np.clip(-2 * yaw, -.35, .35) + + self.action = action + self.elapsed += 1 + if self.elapsed >= duration and self.phase < len(self.PHASES) - 1: + self.phase += 1 + self.elapsed = 0 + self.start = action.copy() + return action.astype(np.float32) diff --git a/policies/sandwich_remove/astra-s2/episodes.csv b/policies/sandwich_remove/astra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..cf777f3f49d60ac5925cd99131a3ff60393c8ef3 --- /dev/null +++ b/policies/sandwich_remove/astra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,3150,timeout,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,629,terminated,0 +620009,0,3150,timeout,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,0,3150,timeout,0 +620014,0,3150,timeout,0 +620015,0,3150,timeout,0 +620016,0,3150,timeout,0 +620017,0,3150,timeout,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,3150,timeout,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,3150,timeout,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,3150,timeout,0 +620031,0,3150,timeout,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,3150,timeout,0 +620043,0,3150,timeout,0 +620044,0,3150,timeout,0 +620045,0,602,terminated,0 +620046,0,3150,timeout,0 +620047,0,3150,timeout,0 +620048,0,3150,timeout,0 +620049,0,3150,timeout,0 +620050,0,3150,timeout,0 +620051,0,3150,timeout,0 +620052,0,3150,timeout,0 +620053,0,3150,timeout,0 +620054,0,596,terminated,0 +620055,0,3150,timeout,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,3150,timeout,0 +620059,0,3150,timeout,0 +620060,0,3150,timeout,0 +620061,0,3150,timeout,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,0,3150,timeout,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,3150,timeout,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,3150,timeout,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,3150,timeout,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,0,3150,timeout,0 +620084,0,3150,timeout,0 +620085,0,3150,timeout,0 +620086,0,3150,timeout,0 +620087,0,3150,timeout,0 +620088,0,3150,timeout,0 +620089,0,3150,timeout,0 +620090,0,3150,timeout,0 +620091,0,3150,timeout,0 +620092,0,3150,timeout,0 +620093,0,3150,timeout,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,0,3150,timeout,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/astra-s2/policy.py b/policies/sandwich_remove/astra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..df0cab82b9e83e6d11df5f98e824da1eab2be361 --- /dev/null +++ b/policies/sandwich_remove/astra-s2/policy.py @@ -0,0 +1,109 @@ +"""Deterministic, hand-written upper-body manipulation controller. + +The base uses proprioceptive position feedback. Arm motions are staged joint +commands, with constants tuned in the simulator. No demonstration files or +learned components are used at run time. +""" +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.hold = np.array(tools.hold_action()) + self.start = obs['low_dim_obs'][21:25].copy() + + @staticmethod + def blend(start, end, fraction): + start = np.asarray(start, dtype=float) + return start + (np.asarray(end, dtype=float) - start) * min(1.0, fraction) + + def drive(self, action, obs, target, speed=0.22): + pose = obs['low_dim_obs'][21:25] + delta = np.asarray(target) - pose[:2] + c, s = np.cos(pose[3]), np.sin(pose[3]) + velocity = np.array([[c, s], [-s, c]]) @ delta * 2 + velocity = np.clip(velocity, -speed, speed) + for k in range(2): + if abs(delta[k]) < .012: + velocity[k] = 0 + elif 0 < abs(velocity[k]) < .065: + velocity[k] = np.sign(velocity[k]) * .065 + action[:2] = velocity + action[3] = np.clip(-5 * pose[3], -.6, .6) + + def act(self, obs, tools): + t = int(obs['t']) + action = self.hold.copy() + action[19:21] = 0 + raised = [-1.3, 0, 0, .5, 0, 0, 0] + + # Retreat before raising the arms, then approach with worktop clearance. + if t < 260: + pose = obs['low_dim_obs'][21:25] + if t < 55: + target = [-.22, self.start[1]] + else: + action[5:12] = raised + action[12:19] = raised + target = [-.22, self.start[1]] if t < 120 else [.20, .25] + delta = np.array(target) - pose[:2] + c, s = np.cos(pose[3]), np.sin(pose[3]) + velocity = np.array([[c, s], [-s, c]]) @ delta * 2 + velocity = np.clip(velocity, -.3, .3) + velocity[np.abs(velocity) < .035] = 0 + for k in range(2): + if 0 < abs(velocity[k]) < .065: + velocity[k] = np.sign(velocity[k]) * .065 + action[:2] = velocity + action[3] = np.clip(-pose[3] * 2, -.3, .3) + return action + + # Approach the spatula handle, close, and lift. + action[5:12] = raised + if t < 455: + above = [-1.1, -.1, .2, .5, 0, 0, 0] + grasp = [-.3, -.1, .2, .6, 0, 0, 0] + if t < 300: + action[12:19] = above + elif t < 370: + action[12:19] = self.blend(above, grasp, (t - 299) / 45) + elif t < 395: + action[12:19] = grasp + action[20] = 1 + else: + action[12:19] = [-1.3, -.1, .2, .5, 0, 0, 0] + action[20] = 1 + return action + + # Park the spatula and acquire the pan handle with the left hand. + action[20] = 1 + action[12:19] = [-1.3, -.35, 0, .5, 0, 0, 0] + grasp = [-.55, .05, .2, .6, 0, 0, 0] + carry = [-1.1, .05, .2, .5, 0, .65, 0] + if t >= 505: + action[5:12] = self.blend(raised, grasp, (t - 504) / 45) + if t >= 575: + action[19] = 1 + action[5:12] = grasp + if t >= 600: + action[5:12] = self.blend(grasp, carry, (t - 599) / 60) + if t >= 650: + action[12] = -1.3 - .6 * min(1, (t - 649) / 40) + + # Carry along the counter using measured base position and yaw. + if t >= 680: + self.drive(action, obs, [.20, -.6]) + if t >= 1300: + action[:2] = 0 + action[3] = 0 + action[5:12] = carry + action[10] = .65 - 1.95 * min(1, (t - 1299) / 70) + if t >= 1450: + action[5] = -.75 + if t >= 1800: + action[5] = -.5 + action[10] = 1.5 if ((t - 1800) // 65) % 2 == 0 else -1.3 + if t >= 2190: + action[19] = 0 + action[5:12] = [-1.3, .6, 0, .5, 0, 0, 0] + return action diff --git a/policies/sandwich_remove/astra-s3/episodes.csv b/policies/sandwich_remove/astra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..1d90faa621fa689574d20d07bcce8fca0fbe69a1 --- /dev/null +++ b/policies/sandwich_remove/astra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,3150,timeout,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,3150,timeout,0 +620009,0,3150,timeout,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,0,3150,timeout,0 +620014,0,3150,timeout,0 +620015,0,3150,timeout,0 +620016,0,3150,timeout,0 +620017,0,3150,timeout,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,3150,timeout,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,3150,timeout,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,3150,timeout,0 +620031,0,3150,timeout,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,3150,timeout,0 +620043,0,3150,timeout,0 +620044,0,3150,timeout,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,0,3150,timeout,0 +620048,0,3150,timeout,0 +620049,0,3150,timeout,0 +620050,0,3150,timeout,0 +620051,0,3150,timeout,0 +620052,0,3150,timeout,0 +620053,0,3150,timeout,0 +620054,0,3150,timeout,0 +620055,0,3150,timeout,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,3150,timeout,0 +620059,0,3150,timeout,0 +620060,0,3150,timeout,0 +620061,0,3150,timeout,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,0,3150,timeout,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,3150,timeout,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,3150,timeout,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,3150,timeout,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,0,3150,timeout,0 +620084,0,1178,terminated,0 +620085,0,3150,timeout,0 +620086,0,3150,timeout,0 +620087,0,3150,timeout,0 +620088,0,3150,timeout,0 +620089,0,3150,timeout,0 +620090,0,3150,timeout,0 +620091,0,3150,timeout,0 +620092,0,3150,timeout,0 +620093,0,3150,timeout,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,0,3150,timeout,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/astra-s3/policy.py b/policies/sandwich_remove/astra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..3fc768b77c17604879172726690e081a28e8e62d --- /dev/null +++ b/policies/sandwich_remove/astra-s3/policy.py @@ -0,0 +1,107 @@ +"""Deterministic visual grasping and smooth, feedback-controlled manipulation.""" +import cv2 +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.action = np.asarray(tools.hold_action(), dtype=np.float64).copy() + self.target = self.action.copy() + self.stage = -1 + self.started = int(obs['t']) + self.elapsed = 0 + self.goal = None + self.grasp_roll = .04 + # Durations are control ticks. Joint poses are manually specified. + self.program = [ + (160, {'goal': (-.18, .25, 0)}), + (80, {'right': (-.7, 0, 0, .4, 0, 0, 0), 'grip': 0}), + (190, {'goal': (.12, .25, 0)}), + (60, {'goal': None, 'right': (-.7, .04, 0, .4, 0, 0, 0), 'align': True}), + (60, {'right': (-.65, .04, 0, .4, 0, 0, 0), 'grip': .6}), + (60, {'grip': 1}), + (80, {'right': (-1, .04, 0, .4, 0, 0, 0)}), + ] + # Reach the pan handle with a vertical jaw opening before scooping. + self.program += [ + (100, {'right': (-1.3, -.2, 0, .4, 0, 0, 0), 'left': (-.9, 0, 0, .4, 1.57, 0, 0), 'left_grip': .6}), + (110, {'goal': (.17, .25, 0), 'left': (-.65, 0, 0, .4, 1.57, 0, 0)}), + (60, {'goal': None, 'left_grip': 1}), + (100, {'left': (-1, 0, 0, .4, 1.57, 0, 0)}), + ] + self.add_transfer(.6) + self.program += [ + (180, {'left': (-1, 0, 0, .4, 2.1, 0, 0), 'right': (-.65, .15, 0, .4, 0, .15, 0)}), + (180, {'right': (-.65, -.2, 0, .4, 0, .15, 0)}), + (120, {'right': (-1.1, 0, 0, .4, 0, 0, 0)}), + (500, {'goal': None}), + ] + + def add_transfer(self, depth): + self.program.extend([ + (100, {'goal': None, 'right': (-.8, .18, 0, .4, 0, .15, 0), 'left': (-1, 0, 0, .4, 1.57, 0, 0)}), + (100, {'right': (-depth, .18, 0, .4, 0, 0, 0)}), + (160, {'right': (-depth, -.16, 0, .4, 0, 0, 0)}), + (100, {'right': (-1, -.16, 0, .4, 0, .4, 0)}), + (290, {'goal': (.12, -.42, 0)}), + (100, {'goal': None, 'right': (-.6, 0, 0, .4, 0, 0, 0)}), + (120, {'right': (-.7, 0, 0, .4, .9, .3, 0)}), + (100, {'right': (-1.15, 0, 0, .4, 0, 0, 0)}), + ]) + + def align_handle(self, tools): + im = np.asarray(tools.image('right_wrist')).astype(np.float32) + r, g, b = im[:, :, 0], im[:, :, 1], im[:, :, 2] + mask = ((r > 1.45*g) & (g > 1.2*b) & (r > 70) & (g > 25)).astype(np.uint8) + n, labels, stats, centers = cv2.connectedComponentsWithStats(mask) + candidates = [i for i in range(1, n) if stats[i, cv2.CC_STAT_AREA] >= 15 and stats[i, cv2.CC_STAT_HEIGHT] > 8] + if candidates: + i = max(candidates, key=lambda j: stats[j, cv2.CC_STAT_HEIGHT]) + ys, xs = np.where(labels == i) + endpoint = float(np.median(xs[ys >= np.max(ys)-4])) + self.grasp_roll = float(np.clip(.0028*(42-endpoint), -.1, .14)) + + def enter(self, tools): + settings = self.program[self.stage][1] + if settings.get('align'): + self.align_handle(tools) + if 'goal' in settings: + self.goal = settings['goal'] + if 'right' in settings: + self.target[12:19] = settings['right'] + self.target[13] += self.grasp_roll-.04 + if 'left' in settings: + self.target[5:12] = settings['left'] + if 'left_grip' in settings: + self.target[19] = settings['left_grip'] + if 'grip' in settings: + self.target[20] = settings['grip'] + + def act(self, obs, tools): + t = int(obs['t']) - self.started + if self.stage < 0: + self.stage = 0 + self.enter(tools) + while self.stage + 1 < len(self.program) and t - self.elapsed >= self.program[self.stage][0]: + self.elapsed += self.program[self.stage][0] + self.stage += 1 + self.enter(tools) + self.target[:2] = 0 + self.target[3] = 0 + self.target[2] = .74 + self.target[4] = 0 + if self.goal is not None and not obs['fell']: + p = np.asarray(obs['low_dim_obs'])[21:25] + dx, dy = np.asarray(self.goal[:2]) - p[:2] + c, s = np.cos(p[3]), np.sin(p[3]) + v = np.clip(2*np.array((c*dx+s*dy, -s*dx+c*dy)), -.22, .22) + v[np.abs(v) < .025] = 0 + small = (np.abs(v) >= .025) & (np.abs(v) < .06) + v[small] = np.sign(v[small])*.06 + self.target[:2] = v + error = (self.goal[2]-p[3]+np.pi) % (2*np.pi)-np.pi + self.target[3] = np.clip(2*error, -.4, .4) + self.action[5:19] += np.clip(self.target[5:19]-self.action[5:19], -.012, .012) + self.action[:5] = self.target[:5] + self.action[19:] = self.target[19:] + return self.action.astype(np.float32).copy() diff --git a/policies/sandwich_remove/deepseek1017-s1/episodes.csv b/policies/sandwich_remove/deepseek1017-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..2870178ebb17fedea06418a056bd8ec94f2f3b5c --- /dev/null +++ b/policies/sandwich_remove/deepseek1017-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,3150,timeout,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,3150,timeout,0 +620009,0,3150,timeout,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,0,3150,timeout,0 +620014,0,3150,timeout,0 +620015,0,3150,timeout,0 +620016,0,3150,timeout,0 +620017,0,3150,timeout,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,3150,timeout,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,3150,timeout,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,3150,timeout,0 +620031,0,3150,timeout,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,3150,timeout,0 +620043,0,3150,timeout,0 +620044,0,3150,timeout,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,0,3150,timeout,0 +620048,0,3150,timeout,0 +620049,0,3150,timeout,0 +620050,0,3150,timeout,0 +620051,0,3150,timeout,0 +620052,0,3150,timeout,0 +620053,0,3150,timeout,0 +620054,0,3150,timeout,0 +620055,0,3150,timeout,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,3150,timeout,0 +620059,0,3150,timeout,0 +620060,0,3150,timeout,0 +620061,0,3150,timeout,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,0,3150,timeout,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,3150,timeout,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,3150,timeout,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,3150,timeout,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,0,3150,timeout,0 +620084,0,3150,timeout,0 +620085,0,3150,timeout,0 +620086,0,3150,timeout,0 +620087,0,3150,timeout,0 +620088,0,3150,timeout,0 +620089,0,3150,timeout,0 +620090,0,3150,timeout,0 +620091,0,3150,timeout,0 +620092,0,3150,timeout,0 +620093,0,3150,timeout,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,0,3150,timeout,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/deepseek1017-s1/policy.py b/policies/sandwich_remove/deepseek1017-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c10b18a75542ed1d1bd33bf9836df580480bbd5b --- /dev/null +++ b/policies/sandwich_remove/deepseek1017-s1/policy.py @@ -0,0 +1,191 @@ +"""Hand-written control policy for the Unitree G1 sandwich task. + +Task: use the spatula to move the sandwich out of the frying pan and onto the +chopping board that lies on the near counter edge between the robot and the pan. + +The scene is fixed and only the small placement of the spatula / sandwich in +the pan varies with the seed, so the controller is built from closed-loop +primitives rather than from a learned model: + + * hold a commanded world stance with the base controller (pelvis feedback), + * raise the arms into a walking posture clear of the counter, + * walk up to the cook-top with a forward lean, + * sweep both hands down towards the pan, close the parallel jaws while + rolling the wrists so the jaws straddle whatever handle is in reach, + * lift + pull straight back over the near counter edge (where the board is) + while the body backs away, then open the grippers, + * repeat the scoop with several hand / stance variants during the episode, + which covers the per-seed variance of the spatula placement. + +Everything is deterministic: no randomness and no wall-clock time are used. + +Contract (docs/api.md): + reset(obs, tools) once per episode + act(obs, tools) -> 21 floats at 50 Hz +""" + +import math + +import numpy as np + + +class Policy: + """Deterministic scripted controller with pelvis / heading feedback.""" + + # walking posture: arms held high, clear of the counter + LEFT_UP = (2.40, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00) + RIGHT_OUT = (1.10, 0.00, 0.00, 0.30, 0.00, 0.00, 0.00) + + # attempt variants: + # (stance x, stance y, stance yaw, torso pitch, + # shoulder pitch, shoulder roll, elbow, close_gripper) + ATTEMPTS = ( + (0.35, 0.29, 0.00, 0.55, 0.80, 0.25, -0.35, 1), + (0.35, 0.24, -0.10, 0.50, 1.05, 0.20, -0.30, 1), + (0.37, 0.34, 0.10, 0.45, 0.65, 0.35, -0.45, 1), + (0.30, 0.29, 0.00, 0.60, 0.55, 0.10, -0.55, 1), + (0.38, 0.27, 0.05, 0.35, 1.35, 0.30, -0.30, 0), + (0.33, 0.31, -0.05, 0.55, 0.90, 0.20, -0.45, 1), + (0.36, 0.22, -0.15, 0.50, 1.15, 0.45, -0.35, 0), + (0.34, 0.36, 0.10, 0.58, 0.75, 0.15, -0.40, 1), + ) + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float64) + self.t = 0 + self.phase = 0 + self.phase_t = 0 + self.attempt = 0 + self.fell = False + + # ------------------------------------------------------------------ util + def _base(self, obs, tx, ty, tyaw): + """Body-frame velocity command that drives the pelvis to (tx,ty,tyaw).""" + ld = obs["low_dim_obs"] + x, y, yaw = float(ld[21]), float(ld[22]), float(ld[24]) + ex, ey = tx - x, ty - y + eyaw = (tyaw - yaw + math.pi) % (2.0 * math.pi) - math.pi + c, s = math.cos(yaw), math.sin(yaw) + vx = 1.4 * (c * ex + s * ey) + vy = 1.4 * (-s * ex + c * ey) + wz = 1.6 * eyaw + if abs(vx) < 0.055 and abs(vy) < 0.055: + vx = vy = 0.0 + if abs(wz) < 0.08: + wz = 0.0 + return ( + float(np.clip(vx, -0.32, 0.32)), + float(np.clip(vy, -0.32, 0.32)), + float(np.clip(wz, -0.4, 0.4)), + ) + + @staticmethod + def _mix(a, b, f): + f = max(0.0, min(1.0, f)) + return tuple(a[i] + (b[i] - a[i]) * f for i in range(len(a))) + + def _go(self): + self.phase += 1 + self.phase_t = 0 + + # ---------------------------------------------------------------- policy + def act(self, obs, tools): + self.t += 1 + self.phase_t += 1 + if obs.get("fell"): + self.fell = True + + raw = np.array(self.hold, dtype=np.float64) + raw[2] = 0.74 + if self.fell: + return raw.astype(np.float32) + + p = self.phase + n = self.phase_t + tx, ty, tyaw, pitch, sp, roll, el, grip = self.ATTEMPTS[self.attempt] + # both arms reach forward; each uses its free (outward) roll direction + left_reach = (sp, roll, 0.0, el, 0.0, 0.0, 0.0) + right_reach = (sp, -roll, 0.0, el, 0.0, 0.0, 0.0) + + # 0 - raise both arms into the walking posture + if p == 0: + raw[4] = 0.20 + raw[5:12] = self.LEFT_UP + raw[12:19] = self.RIGHT_OUT + raw[19] = raw[20] = 0.0 + if n > 45: + self._go() + + # 1 - walk forward to the counter in front of the pan + elif p == 1: + vx, vy, wz = self._base(obs, 0.36, 0.29, 0.0) + x = float(obs["low_dim_obs"][21]) + if x < 0.35: + vx = max(vx, 0.22) + if x > 0.39: + vx = min(vx, -0.10) + raw[0], raw[1], raw[3] = vx, vy, wz + raw[4] = 0.20 + raw[5:12] = self.LEFT_UP + raw[12:19] = self.RIGHT_OUT + raw[19] = raw[20] = 0.0 + if n > 190 or (x >= 0.35 and abs(vx) < 0.06): + self._go() + + # 2 - lean over the counter, lower both hands towards the pan + elif p == 2: + vx, vy, wz = self._base(obs, tx, ty, tyaw) + raw[0], raw[1], raw[3] = vx, vy, wz + raw[4] = pitch + f = n / 38.0 + raw[5:12] = self._mix(self.LEFT_UP, left_reach, f) + raw[12:19] = self._mix(self.RIGHT_OUT, right_reach, f) + raw[19] = raw[20] = 0.0 + if n > 45: + self._go() + + # 3 - close the jaws while rolling the wrists around the handle + elif p == 3: + vx, vy, wz = self._base(obs, tx, ty, tyaw) + raw[0], raw[1], raw[3] = vx, vy, wz + raw[4] = pitch + f = min(1.0, n / 30.0) + wr = -1.3 + 2.6 * f + raw[5:12] = (sp, roll, 0.0, el, -wr, 0.0, 0.0) + raw[12:19] = (sp, -roll, 0.0, el, wr, 0.0, 0.0) + raw[19] = 1.0 if grip else 0.0 + raw[20] = 1.0 if grip else 0.0 + if n > 40: + self._go() + + # 4 - lift and pull straight back over the near edge (the board) + elif p == 4: + f = min(1.0, n / 45.0) + vx, vy, wz = self._base(obs, 0.14, ty, tyaw) + raw[0], raw[1], raw[3] = vx, vy, wz + raw[4] = 0.30 + raw[5:12] = self._mix(left_reach, + (0.25, roll * 0.5, 0.0, -0.25, 0.0, 0.0, 0.0), + f) + raw[12:19] = self._mix(right_reach, + (0.25, -roll * 0.5, 0.0, -0.25, 0.0, 0.0, 0.0), + f) + raw[19] = 1.0 if grip else 0.0 + raw[20] = 1.0 if grip else 0.0 + if n > 55: + self._go() + + # 5 - release and retract + elif p == 5: + vx, vy, wz = self._base(obs, 0.10, ty, tyaw) + raw[0], raw[1], raw[3] = vx, vy, wz + raw[4] = 0.15 + raw[5:12] = (0.10, 0.0, 0.0, -0.15, 0.0, 0.0, 0.0) + raw[12:19] = (0.10, 0.0, 0.0, -0.15, 0.0, 0.0, 0.0) + raw[19] = raw[20] = 0.0 + if n > 35: + self.attempt = (self.attempt + 1) % len(self.ATTEMPTS) + self.phase = 1 + self.phase_t = 0 + + return np.asarray(raw, dtype=np.float32) diff --git a/policies/sandwich_remove/deepseek1017-s2/episodes.csv b/policies/sandwich_remove/deepseek1017-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..ec1f58f7d963c63eaba366a80239b61c074fbb50 --- /dev/null +++ b/policies/sandwich_remove/deepseek1017-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,324,terminated,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,324,terminated,0 +620009,0,3150,timeout,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,0,324,terminated,0 +620014,0,3150,timeout,0 +620015,0,403,terminated,0 +620016,0,3150,timeout,0 +620017,0,3150,timeout,0 +620018,0,3150,timeout,0 +620019,0,339,terminated,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,3150,timeout,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,3150,timeout,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,354,terminated,0 +620031,0,324,terminated,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,3150,timeout,0 +620043,0,3150,timeout,0 +620044,0,3150,timeout,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,0,324,terminated,0 +620048,0,3150,timeout,0 +620049,0,3150,timeout,0 +620050,0,3150,timeout,0 +620051,0,349,terminated,0 +620052,0,3150,timeout,0 +620053,0,324,terminated,0 +620054,0,3150,timeout,0 +620055,0,3150,timeout,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,3150,timeout,0 +620059,0,3150,timeout,0 +620060,0,3150,timeout,0 +620061,0,3150,timeout,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,0,3150,timeout,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,499,terminated,0 +620071,0,3150,timeout,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,3150,timeout,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,403,terminated,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,0,354,terminated,0 +620084,0,324,terminated,0 +620085,0,3150,timeout,0 +620086,0,3150,timeout,0 +620087,0,3150,timeout,0 +620088,0,324,terminated,0 +620089,0,3150,timeout,0 +620090,0,3150,timeout,0 +620091,0,3150,timeout,0 +620092,0,486,terminated,0 +620093,0,3150,timeout,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,324,terminated,0 +620097,0,3150,timeout,0 +620098,0,3150,timeout,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/deepseek1017-s2/policy.py b/policies/sandwich_remove/deepseek1017-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..e38f8a4a9478d5dec33032f5f2dcf4a4a3b2e914 --- /dev/null +++ b/policies/sandwich_remove/deepseek1017-s2/policy.py @@ -0,0 +1,162 @@ +"""Hand-written control policy for the G1 sandwich-remove task. + +The scene is fixed across development seeds, so the policy uses a tuned +open-loop skeleton with a proprioceptive closed loop on the base: + + * walk to the counter and line up with the pan using a world-frame + proportional controller on the measured pelvis pose (the frozen walking + controller has lag and wobble, so the pelvis pose is read every step), + * sweep the right arm through a short sequence of poses that places the + gripper just above the spatula handle, + * push the hand a couple of centimetres further so the handle sits deep + between the fingers, close the gripper, + * lift the spatula clear of the pan, draw it back over the chopping + surface and release it. + +No learned components are used; every step is analytic control. All +constants were tuned by running episodes against the development seeds. +""" + +import numpy as np + + +def _wrap(a): + return (a + np.pi) % (2.0 * np.pi) - np.pi + + +class Policy: + """Deterministic scripted controller.""" + + # (shoulder_pitch, elbow, wrist_pitch, height) pre-grasp sweep + PROBES = ( + (-0.90, 0.00, 1.20, 0.80), + (-1.10, 0.00, 1.20, 0.80), + (-0.90, 0.10, 1.00, 0.80), + (-0.70, 0.00, 1.00, 0.80), + (-0.90, 0.00, 1.20, 0.74), + (-1.10, 0.00, 1.20, 0.74), + (-0.70, 0.10, 1.00, 0.74), + ) + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.arm = self.hold.copy() + self.grip = float(self.hold[20]) + self.height = float(self.hold[2]) + self.phase = 0 + self.pt = 0 + self.hp_y = 0.28 + self.hp_yaw = 0.0 + self.p0 = np.array([self.hold[12], self.hold[15], self.hold[17]]) + + # ------------------------------------------------------------------ + def _base(self, obs, tx, ty, tyaw, kp, kyaw, vmax, wmax): + lo = obs["low_dim_obs"] + x, y = float(lo[21]), float(lo[22]) + yaw = float(lo[24]) + vxw = kp * (tx - x) + vyw = kp * (ty - y) + n = float(np.hypot(vxw, vyw)) + if n > vmax: + vxw *= vmax / n + vyw *= vmax / n + vxb = np.cos(yaw) * vxw + np.sin(yaw) * vyw + vyb = -np.sin(yaw) * vxw + np.cos(yaw) * vyw + wz = float(np.clip(kyaw * _wrap(tyaw - yaw), -wmax, wmax)) + return vxb, vyb, wz + + def _action(self, obs, base, gains): + a = self.arm.copy() + if base is None: + a[0] = a[1] = a[3] = 0.0 + else: + vx, vy, wz = self._base(obs, base[0], base[1], base[2], *gains) + a[0], a[1], a[3] = vx, vy, wz + a[2] = self.height + a[19] = self.hold[19] + a[20] = self.grip + return a + + # ------------------------------------------------------------------ + def act(self, obs, tools): + a = None + ph = self.phase + if ph == 0: # walk to the counter + a = self._action(obs, (0.22, 0.28, 0.0), (1.0, 1.2, 0.25, 0.30)) + self.pt += 1 + if self.pt >= 110: + self.phase, self.pt = 1, 0 + elif ph == 1: # lateral fine approach + k = self.pt // 12 + ty = 0.28 + 0.05 * (min(k, 5) + 1) + a = self._action(obs, (0.15, ty, 0.0), (1.2, 1.2, 0.20, 0.30)) + self.pt += 1 + if self.pt >= 72: + self.hp_y = float(obs["low_dim_obs"][22]) + self.hp_yaw = float(obs["low_dim_obs"][24]) + self.phase, self.pt = 2, 0 + elif ph == 2: # close the remaining distance + a = self._action(obs, (0.19, self.hp_y, 0.0), (1.5, 1.5, 0.25, 0.30)) + self.pt += 1 + if self.pt >= 30: + self.phase, self.pt = 3, 0 + elif ph == 3: # arm pre-grasp sweep + k = self.pt // 18 + if k < len(self.PROBES): + shp, elb, wp, h = self.PROBES[k] + self.arm[12], self.arm[15], self.arm[17] = shp, elb, wp + self.arm[16], self.arm[18] = -0.20, -0.30 + self.height = h + a = self._action(obs, (0.19, self.hp_y, 0.0), + (2.0, 2.0, 0.30, 0.40)) + self.pt += 1 + if self.pt >= 18 * len(self.PROBES): + self.phase, self.pt = 4, 0 + elif ph == 4: # press the handle deep into the jaws + a = self._action(obs, (0.215, self.hp_y, 0.0), + (2.0, 2.0, 0.30, 0.40)) + self.pt += 1 + if self.pt >= 14: + self.phase, self.pt = 5, 0 + elif ph == 5: # close the gripper + self.grip = 1.0 + a = self._action(obs, (0.215, self.hp_y, 0.0), + (2.0, 2.0, 0.30, 0.40)) + self.pt += 1 + if self.pt >= 25: + self.phase, self.pt = 6, 0 + elif ph == 6: # lift the spatula clear of the pan + self.height = 0.74 + 0.005 * (self.pt + 1) + a = self._action(obs, (0.215, self.hp_y, 0.0), + (2.0, 2.0, 0.30, 0.40)) + self.pt += 1 + if self.pt >= 24: + self.p0 = np.array([self.arm[12], self.arm[15], self.arm[17]]) + self.phase, self.pt = 7, 0 + elif ph == 7: # draw the spatula back over the board + t = min(1.0, (self.pt + 1) / 55.0) + end = np.array([-0.30, 0.42, 0.60]) + v = self.p0 + (end - self.p0) * t + self.arm[12], self.arm[15], self.arm[17] = v + self.height = 0.74 + a = self._action(obs, (0.12, self.hp_y - 0.03, 0.0), + (2.0, 2.0, 0.30, 0.40)) + self.pt += 1 + if self.pt >= 55: + self.phase, self.pt = 8, 0 + elif ph == 8: # release over the chopping surface + self.grip = 0.0 + a = self._action(obs, (0.12, self.hp_y - 0.03, 0.0), + (2.0, 2.0, 0.30, 0.40)) + self.pt += 1 + if self.pt >= 30: + self.phase, self.pt = 9, 0 + else: # settle, keep still + self.arm[12], self.arm[15], self.arm[17] = 0.0, 0.0, 0.0 + self.height = 0.74 + a = self._action(obs, (0.05, self.hp_y - 0.03, 0.0), + (2.0, 2.0, 0.30, 0.40)) + + if a is None: # safety: hold the current pose + a = self.hold.copy() + return np.asarray(a, dtype=np.float32) diff --git a/policies/sandwich_remove/deepseek1017-s3/episodes.csv b/policies/sandwich_remove/deepseek1017-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..35d0d512b382aa4ee2ea2cc021d4cbaadcae7c04 --- /dev/null +++ b/policies/sandwich_remove/deepseek1017-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,216,terminated,0 +620002,0,179,terminated,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,3150,timeout,0 +620009,0,3150,timeout,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,0,3150,timeout,0 +620014,0,3150,timeout,0 +620015,0,3150,timeout,0 +620016,0,3150,timeout,0 +620017,0,3150,timeout,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,3150,timeout,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,175,terminated,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,3150,timeout,0 +620031,0,3150,timeout,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,3150,timeout,0 +620043,0,3150,timeout,0 +620044,0,3150,timeout,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,0,3150,timeout,0 +620048,0,3150,timeout,0 +620049,0,3150,timeout,0 +620050,0,3150,timeout,0 +620051,0,3150,timeout,0 +620052,0,3150,timeout,0 +620053,0,3150,timeout,0 +620054,0,3150,timeout,0 +620055,0,167,terminated,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,3150,timeout,0 +620059,0,173,terminated,0 +620060,0,206,terminated,0 +620061,0,3150,timeout,0 +620062,0,175,terminated,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,0,3150,timeout,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,3150,timeout,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,238,terminated,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,3150,timeout,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,176,terminated,0 +620083,0,3150,timeout,0 +620084,0,3150,timeout,0 +620085,0,166,terminated,0 +620086,0,3150,timeout,0 +620087,0,221,terminated,0 +620088,0,3150,timeout,0 +620089,0,3150,timeout,0 +620090,0,3150,timeout,0 +620091,0,3150,timeout,0 +620092,0,167,terminated,0 +620093,0,3150,timeout,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,0,228,terminated,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/deepseek1017-s3/policy.py b/policies/sandwich_remove/deepseek1017-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..f356c6a8f0d5b99ef003a420275d8ef5f9e7120c --- /dev/null +++ b/policies/sandwich_remove/deepseek1017-s3/policy.py @@ -0,0 +1,287 @@ +"""Hand-written control policy for the G1 sandwich-spatula task. + +The strategy is a fixed sequence tuned against the robot's own cameras: + + * squat in place (prevents the base drifting away while the arms rise), + * raise both arms into the pan area with open grippers, + * press forward until the hands are over the pan, + * lower the hands into the pan, close both grippers, and lift, + * repeat the lower/sweep/lift once more to scoop with the spatula, + * carry sideways along the counter to the chopping board, + * lower the hands, release, and retract. + +All motion is closed-loop on the pelvis pose (read from low_dim_obs) for +heading/position hold. No randomness and no wall-clock time is used, so the +episode is reproducible. +""" + +import numpy as np + + +# Way-points for the arm raise (left / right), same joint order as the action. +_L1 = np.array([-0.8, 0.0, 0.0, 0.4, 0.0, 0.0, 0.0]) +_L2 = np.array([-1.0, -0.2, 0.0, 0.5, 0.0, 0.0, 0.0]) +_L3 = np.array([-1.1, -0.3, 0.0, 0.6, 0.0, 0.0, 0.0]) +_R1 = np.array([-0.5, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0]) +_R2 = np.array([-0.8, 0.0, 0.0, 0.4, 0.0, 0.0, 0.0]) +_R3 = np.array([-1.1, 0.0, 0.0, 0.4, 0.0, 0.0, 0.0]) + +# Hands lowered into the pan (elbows bent, pelvis a little lower). +_TL = np.array([-1.0, -0.2, 0.0, 1.1, 0.0, 0.0, 0.0]) +_TR = np.array([-1.0, 0.0, 0.0, 1.1, 0.0, 0.0, 0.0]) + +# Retracted carry pose. +_CL = np.array([-0.7, -0.1, 0.0, 0.3, 0.0, 0.0, 0.0]) +_CR = np.array([-0.7, 0.0, 0.0, 0.3, 0.0, 0.0, 0.0]) + +# Lowered / releasing pose over the chopping board. +_PL = np.array([-0.9, -0.1, 0.0, 0.9, 0.5, 0.0, 0.0]) +_PR = np.array([-0.9, 0.0, 0.0, 0.9, 0.5, 0.0, 0.0]) + +_ZERO = np.zeros(7, dtype=np.float32) + + +def _lerp(a, b, f): + f = float(np.clip(f, 0.0, 1.0)) + return a * (1.0 - f) + b * f + + +class Policy: + """Fixed, deterministic script with pose feedback on the base.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = "squat" + self.pt = 0 + self.larm = _ZERO.copy() + self.rarm = _ZERO.copy() + self.grip_l = 0.6 + self.grip_r = 0.6 + self.height = 0.74 + self.pitch = 0.1 + self.strafe_done = False + self.scoop = 0 + + # ------------------------------------------------------------------ helpers + def _yaw_cmd(self, obs): + yaw = float(obs["low_dim_obs"][24]) + wz = float(np.clip(-1.5 * yaw, -0.4, 0.4)) + if abs(wz) < 0.06: + wz = 0.0 + return wz + + def _action(self, obs, vx=0.0, vy=0.0, wz=None): + a = self.hold.copy() + a[0] = vx + a[1] = vy + a[2] = self.height + a[3] = self._yaw_cmd(obs) if wz is None else wz + a[4] = self.pitch + a[5:12] = self.larm + a[12:19] = self.rarm + a[19] = self.grip_l + a[20] = self.grip_r + return a + + # ------------------------------------------------------------------- policy + def act(self, obs, tools): + lo = obs["low_dim_obs"] + x = float(lo[21]) + y = float(lo[22]) + self.pt += 1 + + # ---- phase 1: walk to the counter ----------------------------------- + if self.phase == "approach": + self.height, self.pitch = 0.74, 0.1 + a = self._action(obs, vx=0.3) + if self.pt >= 60: + self.phase = "squat" + self.pt = 0 + return a + + # ---- phase 2: squat in place before raising the arms ---------------- + if self.phase == "squat": + self.height, self.pitch = 0.70, 0.1 + a = self._action(obs) + if self.pt >= 20: + self.phase = "raise" + self.pt = 0 + return a + + # ---- phase 3: raise both arms over the pan -------------------------- + if self.phase == "raise": + self.height, self.pitch = 0.70, 0.1 + self.grip_l = 0.0 + self.grip_r = 0.0 + k = self.pt + if k <= 20: + f = k / 20.0 + self.larm = _lerp(_ZERO, _L1, f) + self.rarm = _lerp(_ZERO, _R1, f) + elif k <= 40: + f = (k - 20) / 20.0 + self.larm = _lerp(_L1, _L2, f) + self.rarm = _lerp(_R1, _R2, f) + else: + f = min(1.0, (k - 40) / 20.0) + self.larm = _lerp(_L2, _L3, f) + self.rarm = _lerp(_R2, _R3, f) + a = self._action(obs) + if self.pt >= 60: + self.phase = "press" + self.pt = 0 + return a + + # ---- phase 4: press forward into the pan ---------------------------- + if self.phase == "press": + self.height, self.pitch = 0.70, 0.1 + self.grip_l = 0.0 + self.grip_r = 0.0 + self.larm = _L3.copy() + self.rarm = _R3.copy() + a = self._action(obs, vx=0.4) + if self.pt >= 45: + self.phase = "lower" + self.pt = 0 + return a + + # ---- phase 5: lower hands into the pan ------------------------------ + if self.phase == "lower": + f = self.pt / 25.0 + self.height = 0.70 - 0.08 * min(1.0, f) + self.pitch = 0.1 + self.larm = _lerp(_L3, _TL, f) + self.rarm = _lerp(_R3, _TR, f) + self.grip_l = 0.0 + self.grip_r = 0.0 + a = self._action(obs) + if self.pt >= 25: + self.phase = "close" + self.pt = 0 + return a + + # ---- phase 6: close both grippers ----------------------------------- + if self.phase == "close": + self.height, self.pitch = 0.62, 0.1 + self.larm = _TL.copy() + self.rarm = _TR.copy() + self.grip_l = 1.0 + self.grip_r = 1.0 + a = self._action(obs) + if self.pt >= 18: + self.phase = "lift" + self.pt = 0 + return a + + # ---- phase 7: lift the scoop ---------------------------------------- + if self.phase == "lift": + f = self.pt / 30.0 + self.height = 0.62 + 0.08 * min(1.0, f) + self.pitch = 0.1 + self.larm = _lerp(_TL, _CL, f) + self.rarm = _lerp(_TR, _CR, f) + self.grip_l = 1.0 + self.grip_r = 1.0 + a = self._action(obs) + if self.pt >= 30: + if self.scoop == 0: + self.scoop = 1 + self.phase = "lower2" + else: + self.phase = "carry" + self.pt = 0 + return a + + # ---- phase 7: second scoop ------------------------------------------ + if self.phase == "lower2": + f = self.pt / 25.0 + self.height = 0.70 - 0.08 * min(1.0, f) + self.larm = _lerp(_CL, _TL, f) + self.rarm = _lerp(_CR, _TR, f) + self.grip_l = 1.0 + self.grip_r = 1.0 + a = self._action(obs) + if self.pt >= 25: + self.phase = "sweep2" + self.pt = 0 + return a + + # ---- phase 7b: sweep the held spatula through the pan --------------- + if self.phase == "sweep2": + f = min(1.0, self.pt / 25.0) + self.height, self.pitch = 0.62, 0.1 + self.larm = _TL.copy() + self.rarm = _TR.copy() + self.rarm[0] = -1.0 - 0.15 * f + self.rarm[1] = 0.4 * f + self.grip_l = 1.0 + self.grip_r = 1.0 + a = self._action(obs) + if self.pt >= 25: + self.phase = "lift2" + self.pt = 0 + return a + + if self.phase == "lift2": + f = self.pt / 30.0 + self.height = 0.62 + 0.08 * min(1.0, f) + start_r = _TR.copy() + start_r[0] = -1.15 + start_r[1] = 0.4 + self.larm = _lerp(_TL, _CL, f) + self.rarm = _lerp(start_r, _CR, f) + self.grip_l = 1.0 + self.grip_r = 1.0 + a = self._action(obs) + if self.pt >= 30: + self.phase = "carry" + self.pt = 0 + return a + + # ---- phase 8: carry sideways toward the chopping board -------------- + if self.phase == "carry": + self.height, self.pitch = 0.74, 0.1 + self.larm = _CL.copy() + self.rarm = _CR.copy() + self.grip_l = 1.0 + self.grip_r = 1.0 + if (not self.strafe_done) and y > -0.32 and self.pt < 260: + return self._action(obs, vy=-0.3) + self.strafe_done = True + self.phase = "place" + self.pt = 0 + return self._action(obs) + + # ---- phase 9: lower and release over the board ---------------------- + if self.phase == "place": + f = min(1.0, self.pt / 30.0) + self.height = 0.74 - 0.06 * f + self.pitch = 0.1 + self.larm = _lerp(_CL, _PL, f) + self.rarm = _lerp(_CR, _PR, f) + if f > 0.5: + self.grip_l = max(0.0, 1.0 - 2.0 * (f - 0.5)) + self.grip_r = self.grip_l + else: + self.grip_l = 1.0 + self.grip_r = 1.0 + a = self._action(obs) + if self.pt >= 30: + self.phase = "finish" + self.pt = 0 + return a + + # ---- phase 10: retract and hold ------------------------------------- + self.pitch = 0.1 + if self.pt <= 35: + f = self.pt / 35.0 + self.height = 0.68 + 0.06 * f + self.larm = _lerp(_PL, _CL, f) + self.rarm = _lerp(_PR, _CR, f) + else: + self.height = 0.74 + self.larm = _CL.copy() + self.rarm = _CR.copy() + self.grip_l = 0.0 + self.grip_r = 0.0 + return self._action(obs) diff --git a/policies/sandwich_remove/gpt61sol-s1/episodes.csv b/policies/sandwich_remove/gpt61sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..2282aad23c652a4828d04b68cb4f5fcd081f8278 --- /dev/null +++ b/policies/sandwich_remove/gpt61sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,3150,timeout,0 +620003,0,501,terminated,0 +620004,0,3150,timeout,0 +620005,0,503,terminated,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,494,terminated,0 +620009,0,3150,timeout,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,0,502,terminated,0 +620014,0,499,terminated,0 +620015,0,501,terminated,0 +620016,0,404,terminated,0 +620017,0,482,terminated,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,340,terminated,0 +620022,0,340,terminated,0 +620023,0,508,terminated,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,3150,timeout,0 +620028,0,3150,timeout,0 +620029,0,492,terminated,0 +620030,0,3150,timeout,0 +620031,0,3150,timeout,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,344,terminated,0 +620043,0,3150,timeout,0 +620044,0,3150,timeout,0 +620045,0,499,terminated,0 +620046,0,502,terminated,0 +620047,0,3150,timeout,0 +620048,0,3150,timeout,0 +620049,0,500,terminated,0 +620050,0,3150,timeout,0 +620051,0,501,terminated,0 +620052,0,3150,timeout,0 +620053,0,3150,timeout,0 +620054,0,3150,timeout,0 +620055,0,3150,timeout,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,3150,timeout,0 +620059,0,3150,timeout,0 +620060,0,340,terminated,0 +620061,0,3150,timeout,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,0,3150,timeout,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,3150,timeout,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,3150,timeout,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,501,terminated,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,0,3150,timeout,0 +620084,0,507,terminated,0 +620085,0,3150,timeout,0 +620086,0,3150,timeout,0 +620087,0,3150,timeout,0 +620088,0,3150,timeout,0 +620089,0,3150,timeout,0 +620090,0,501,terminated,0 +620091,0,3150,timeout,0 +620092,0,3150,timeout,0 +620093,0,3150,timeout,0 +620094,0,501,terminated,0 +620095,0,3150,timeout,0 +620096,0,508,terminated,0 +620097,0,3150,timeout,0 +620098,0,3150,timeout,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/gpt61sol-s1/policy.py b/policies/sandwich_remove/gpt61sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..691ed1b76b54c77478aafea0417e6944c220446d --- /dev/null +++ b/policies/sandwich_remove/gpt61sol-s1/policy.py @@ -0,0 +1,78 @@ +"""Hand-written deterministic control for transferring a sandwich with a spatula.""" +import cv2 +import numpy as np + +class Policy: + def reset(self, obs, tools): + self.a=np.asarray(tools.hold_action(),dtype=float) + self.a[19:]=0 + self.phase=0;self.start=0;self.source=self.a.copy() + self.yaw_adjust=0.;self.pitch_adjust=0. + def arm(sp,el,wp,roll=0.,height=None,n=80): + return (n,'arm',np.array([sp,-.12,-.5,el,roll,wp,0.]),height) + self.plan=[ + (60,'hoist'),(180,'move',(.13,.247)), + arm(-2.3,.8,.7,n=30),arm(-1.15,.8,.7,n=90), + (35,'align'),(40,'grip'),arm(-1.5,.8,1.05,n=70), + (200,'move',(0.,.29)),(80,'height',.64), + arm(-1.85,.6,1.6,height=.50,n=100),(100,'height',.74), + (360,'move',(.13,-.23)),(100,'height',.63), + arm(-1.85,.6,1.2,n=100),(100,'height',.74), + (120,'move',(-.05,-.23)), + # A second scoop uses a different blade roll while retaining the tool. + (330,'move',(0.,.29)),arm(-1.5,.8,1.05,roll=-.75,n=90), + (80,'height',.67),arm(-1.85,.6,1.6,roll=-.75,height=.53,n=100), + (100,'height',.74),(340,'move',(.13,-.23)), + (100,'height',.64),arm(-1.85,.6,1.2,roll=-.75,n=80), + (100,'height',.74),(100,'move',(-.05,-.23)),(100,'wait')] + + @staticmethod + def handle_hole(im): + hsv=cv2.cvtColor(im,cv2.COLOR_RGB2HSV) + mask=cv2.inRange(hsv,np.array([5,135,55],np.uint8),np.array([24,255,255],np.uint8)) + contours,hierarchy=cv2.findContours(mask,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_SIMPLE) + if hierarchy is None:return None + choices=[] + for i,c in enumerate(contours): + parent=hierarchy[0,i,3] + area=cv2.contourArea(c) + if parent<0 or not 2<=area<=70 or cv2.contourArea(contours[parent])<70:continue + m=cv2.moments(c) + if m['m00']: + u=m['m10']/m['m00'];v=m['m01']/m['m00'] + if 12=self.plan[self.phase][0]: + if self.plan[self.phase][1]=='align': + self.yaw_adjust=self.a[7]+.5 + self.pitch_adjust=self.a[10]-.7 + self.phase+=1;self.start=t;self.source=self.a.copy() + self.a[0:2]=0 + self.a[3]=np.clip(-2*p[3],-.3,.3) + if self.phase>=len(self.plan):return self.a.copy() + item=self.plan[self.phase];dur,kind=item[:2] + f=np.clip((t-self.start+1)/dur,0.,1.) + if kind=='hoist': + self.a[5]=self.a[12]=-2.3 + elif kind=='arm': + target=item[2].copy();target[2]+=self.yaw_adjust + target[5]=np.clip(target[5]+self.pitch_adjust,-1.6,1.6) + self.a[5:12]=self.source[5:12]*(1-f)+target*f + if item[3] is not None:self.a[2]=self.source[2]*(1-f)+item[3]*f + elif kind=='height':self.a[2]=self.source[2]*(1-f)+item[2]*f + elif kind=='move': + err=np.asarray(item[2])-p[:2] + world=np.where(np.abs(err)>.014,np.sign(err)*.12,0.) + c,s=np.cos(p[3]),np.sin(p[3]) + self.a[0]=c*world[0]+s*world[1];self.a[1]=-s*world[0]+c*world[1] + elif kind=='align' and (t-self.start)%5==0: + hole=self.handle_hole(tools.image('left_wrist')) + if hole is not None: + u,v=hole + self.a[7]=np.clip(self.a[7]-.002*(u-31),-.65,-.35) + self.a[10]=np.clip(self.a[10]+.002*(v-75),.6,.85) + elif kind=='grip':self.a[19]=1. + return self.a.copy() diff --git a/policies/sandwich_remove/gpt61sol-s2/episodes.csv b/policies/sandwich_remove/gpt61sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..2e35ae79aae6a77c50056700b88b5a690a7ca1a7 --- /dev/null +++ b/policies/sandwich_remove/gpt61sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,3150,timeout,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,523,terminated,0 +620009,0,3150,timeout,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,0,3150,timeout,0 +620014,0,3150,timeout,0 +620015,0,3150,timeout,0 +620016,0,3150,timeout,0 +620017,0,3150,timeout,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,3150,timeout,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,3150,timeout,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,3150,timeout,0 +620031,0,3150,timeout,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,3150,timeout,0 +620043,0,3150,timeout,0 +620044,0,3150,timeout,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,0,3150,timeout,0 +620048,0,3150,timeout,0 +620049,0,3150,timeout,0 +620050,0,3150,timeout,0 +620051,0,3150,timeout,0 +620052,0,3150,timeout,0 +620053,0,3150,timeout,0 +620054,0,3150,timeout,0 +620055,0,3150,timeout,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,3150,timeout,0 +620059,0,3150,timeout,0 +620060,0,3150,timeout,0 +620061,0,3150,timeout,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,0,3150,timeout,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,3150,timeout,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,3150,timeout,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,3150,timeout,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,0,3150,timeout,0 +620084,0,3150,timeout,0 +620085,0,3150,timeout,0 +620086,0,3150,timeout,0 +620087,0,3150,timeout,0 +620088,0,3150,timeout,0 +620089,0,3150,timeout,0 +620090,0,3150,timeout,0 +620091,0,3150,timeout,0 +620092,0,3150,timeout,0 +620093,0,3150,timeout,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,0,3150,timeout,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/gpt61sol-s2/policy.py b/policies/sandwich_remove/gpt61sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..ac85105861ca3a5230737681fab12bcece85e93e --- /dev/null +++ b/policies/sandwich_remove/gpt61sol-s2/policy.py @@ -0,0 +1,232 @@ +"""Deterministic visual servoing and staged manipulation for the G1. + +Only wrist RGB and proprioception are used. The orange handle opening guides +the spatula pickup; a side approach aligns the pan handle with the left hand. +The remaining stages carry, tip, and scrape over the chopping board. +""" + +import numpy as np +import cv2 + +class Policy: + + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), float) + self.goal = np.array([0.1, 0.247, 0.0]) + self.target = self.a.copy() + self.stage = 'reach' + self.age = 0 + self.good = 0 + self.attempt = 0 + self.hole = None + + def locate(self, im): + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + mask = cv2.inRange(hsv, np.array([4, 105, 65]), np.array([23, 255, 255])) + cs, h = cv2.findContours(mask, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) + if h is None: + return None + candidates = [] + for i, c in enumerate(cs): + if h[0, i, 3] < 0: + continue + M = cv2.moments(c) + ar = M['m00'] + if ar < 2 or ar > 200: + continue + par = cs[h[0, i, 3]] + area = cv2.contourArea(par) + if area < 40: + continue + x, y = (M['m10'] / ar, M['m01'] / ar) + candidates.append((area, x, y, ar)) + if candidates: + _, x, y, ar = max(candidates) + return np.array([x, y, ar]) + return None + + def pan_hole(self, im): + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + m = cv2.inRange(hsv, np.array([0, 0, 0]), np.array([179, 255, 85])) + cs, h = cv2.findContours(m, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE) + if h is None: + return None + best = [] + for i, c in enumerate(cs): + if h[0, i, 3] < 0: + continue + M = cv2.moments(c) + ar = M['m00'] + if not 12 < ar < 800: + continue + cm = np.zeros(m.shape, np.uint8) + cv2.drawContours(cm, [c], -1, 255, -1) + rgb = im[cm > 0].astype(float) + blue = np.mean((rgb[:, 2] > rgb[:, 0] * 1.15) & (rgb[:, 2] > rgb[:, 1] * 0.95)) + x, y = (M['m10'] / ar, M['m01'] / ar) + xx, yy, w, hh = cv2.boundingRect(c) + if blue > 0.4: + best.append((ar, x, y, w)) + if best: + _, x, y, w = max(best) + return np.array([x, y, w]) + return None + + def advance(self, stage): + self.stage = stage + self.age = 0 + self.good = 0 + + def act(self, obs, tools): + t = obs['t'] + self.age += 1 + p = obs['low_dim_obs'] + tar = self.target + tar[2] = 0.74 + tar[4] = 0 + if not self.stage.startswith('pan'): + tar[5:12] = 0 + tar[19] = 0 + if self.stage == 'reach': + tar[12:19] = [-1.3, 0, 0, 0.5, 0, 0, 0] + tar[20] = 0 + self.goal[0] = 0.025 + if self.age >= 160: + self.advance('walk') + elif self.stage == 'walk': + self.goal[0] = 0.1 + if self.age >= 180: + self.advance('lower') + elif self.stage == 'lower': + tar[2] = 0.71 + tar[15] = 0.8 + tar[17] = 0.8 + if self.age >= 160: + self.advance('align') + elif self.stage == 'align': + tar[2] = 0.71 + tar[20] = 0 + if self.age % 10 == 0: + h = self.locate(tools.image('right_wrist')) + self.hole = h + if h is not None: + tar[13] = np.clip(tar[13] + 0.002 * (42 - h[0]), -0.45, 0.45) + tar[17] = np.clip(tar[17] + 0.0015 * (h[1] - 25), 0.4, 1.1) + self.good = self.good + 10 if abs(h[0] - 42) < 5 and abs(h[1] - 25) < 7 else 0 + if self.good >= 10 or self.age >= 350: + self.advance('close') + elif self.stage == 'close': + tar[2] = 0.71 + tar[20] = 1 + if self.age >= 100: + if p[51] < 0.95: + self.advance('lift') + else: + self.attempt += 1 + self.advance('align') + tar[17] -= 0.05 + elif self.stage == 'lift': + tar[2] = 0.77 + tar[12] = -1.4 + tar[20] = 1 + if self.age >= 150: + self.advance('panprep') + elif self.stage == 'panprep': + tar[2] = 0.77 + tar[12] = -1.9 + tar[13] = -0.7 + tar[20] = 1 + tar[5:12] = [-1.5, 0.2, 0, 0.5, 0, 0, 0] + tar[19] = 0 + self.goal[:] = [0.1, 0.82, 0] + if self.age >= 300: + self.advance('panside') + elif self.stage == 'panside': + tar[2] = 0.77 + self.goal[:] = [0.6, 0.82, -np.pi / 2] + if self.age >= 260: + self.advance('panreach') + elif self.stage == 'panreach': + tar[2] = 0.74 + tar[4] = 0.1 + tar[5:12] = [-1.3, 0.19, 0, 0.35, 0, 0.95, 0] + if self.age >= 120: + self.advance('panalign') + elif self.stage == 'panalign': + tar[2] = 0.72 + tar[4] = 0.1 + tar[20] = 1 + tar[19] = 0 + if self.age % 10 == 0: + h = self.pan_hole(tools.image('left_wrist')) + self.hole = h + if h is not None: + tar[6] = np.clip(tar[6] + 0.0015 * (42 - h[0]), -0.1, 0.6) + tar[10] = np.clip(tar[10] + 0.0012 * (h[1] - 25), 0.3, 1.1) + self.good = 10 if abs(h[0] - 42) < 6 and abs(h[1] - 25) < 8 else 0 + else: + tar[10] = min(0.95, tar[10] + 0.015) + if self.good or self.age >= 200: + self.advance('panclose') + elif self.stage == 'panclose': + tar[2] = 0.72 + tar[4] = 0.1 + tar[19] = 1 + tar[20] = 1 + if self.age >= 70: + self.advance('panlift') + elif self.stage == 'panlift': + tar[2] = 0.79 + tar[5] = -1.6 + tar[19] = 1 + tar[20] = 1 + if self.age >= 100: + self.advance('panclear') + elif self.stage == 'panclear': + tar[2] = 0.78 + tar[5] = -1.7 + self.goal[:] = [0.18, 0.82, 0] + if self.age >= 220: + self.advance('panmove') + elif self.stage == 'panmove': + tar[2] = 0.78 + self.goal[:] = [0.18, -0.65, 0] + if self.age >= 350: + self.advance('pandeposit') + elif self.stage == 'pandeposit': + tar[2] = 0.78 + self.goal[:] = [0.3, -0.65, 0] + if self.age >= 150: + self.advance('pantip') + elif self.stage == 'pantip': + tar[2] = 0.74 + tar[5] = -1.1 + tar[9] = 1.4 + tar[10] = -0.8 + if self.age >= 150: + self.advance('panscrape') + elif self.stage == 'panscrape': + tar[2] = 0.74 + tar[12] = -1.3 + tar[13] = -0.03 + tar[15] = 0.8 + tar[17] = 0.8 + if self.age >= 150: + self.advance('pansettle') + else: + tar[2] = 0.77 + tar[19] = 1 + tar[20] = 1 + tar[12] = -1.6 + tar[5] = -1.6 + delta = np.clip(tar - self.a, -0.01, 0.01) + delta[12] = np.clip(tar[12] - self.a[12], -0.026, 0.026) + delta[19:21] = np.clip((tar - self.a)[19:21], -0.1, 0.1) + self.a += delta + c, s = (np.cos(p[24]), np.sin(p[24])) + err = self.goal[:2] - p[21:23] + v = np.clip(3 * err - 0.25 * p[46:48], -0.25, 0.25) + v[np.abs(v) < 0.055] = 0 + self.a[:2] = [c * v[0] + s * v[1], -s * v[0] + c * v[1]] + self.a[3] = np.clip(3 * (self.goal[2] - p[24]), -0.5, 0.5) + return self.a.copy() diff --git a/policies/sandwich_remove/gpt61sol-s3/episodes.csv b/policies/sandwich_remove/gpt61sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..c41ed6c9f886e33316edf53b784c3cdaea793f02 --- /dev/null +++ b/policies/sandwich_remove/gpt61sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,2434,terminated,0 +620001,0,3150,timeout,0 +620002,0,3150,timeout,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,2438,terminated,0 +620008,0,2434,terminated,0 +620009,0,2344,terminated,0 +620010,0,2435,terminated,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,0,3150,timeout,0 +620014,0,1137,terminated,0 +620015,0,3150,timeout,0 +620016,0,3150,timeout,0 +620017,1,2295,success,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,2430,terminated,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,2316,terminated,0 +620027,0,3150,timeout,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,2434,terminated,0 +620031,0,2431,terminated,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,2441,terminated,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,3150,timeout,0 +620043,0,3150,timeout,0 +620044,0,3150,timeout,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,0,3150,timeout,0 +620048,0,3150,timeout,0 +620049,0,3150,timeout,0 +620050,0,3150,timeout,0 +620051,0,3150,timeout,0 +620052,0,3150,timeout,0 +620053,0,2441,terminated,0 +620054,0,2442,terminated,0 +620055,0,3150,timeout,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,1141,terminated,0 +620059,0,3150,timeout,0 +620060,0,3150,timeout,0 +620061,0,3150,timeout,0 +620062,0,2440,terminated,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,0,2441,terminated,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,2433,terminated,0 +620070,0,2569,terminated,0 +620071,0,2439,terminated,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,2441,terminated,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,3150,timeout,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,0,2453,terminated,0 +620084,0,2578,terminated,0 +620085,0,3150,timeout,0 +620086,0,3150,timeout,0 +620087,0,3150,timeout,0 +620088,0,3150,timeout,0 +620089,0,2431,terminated,0 +620090,0,3150,timeout,0 +620091,0,3150,timeout,0 +620092,0,3150,timeout,0 +620093,0,3150,timeout,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,0,2441,terminated,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/gpt61sol-s3/policy.py b/policies/sandwich_remove/gpt61sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d92779b7bdc6467b111af79502b40b92bd3f64eb --- /dev/null +++ b/policies/sandwich_remove/gpt61sol-s3/policy.py @@ -0,0 +1,81 @@ +"""Deterministic camera and joint feedback controller for the kitchen task.""" +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.a = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.i = 0 + self.k = 0 + self.old = self.a.copy() + self.dest = self.a.copy() + # Raise the arms, acquire the spatula, then approach the pan handle. + self.stages = [ + (60, 'set', {19:0,20:0,5:-1.3,12:-1.3,8:.2,15:.2}), + (170, 'walk', (.08,.25)), + (30, 'set', {5:0,8:0}), + (60, 'set', {12:-1.,15:.6}), + (50, 'set', {13:.01}), + (50, 'set', {15:.9}), + (50, 'set', {}), + (40, 'set', {20:1}), + (100, 'lift_tool', {}), + (100, 'ramp', {12:-1.55,13:-.5,5:-1.4,8:.2,6:.15,9:1.57}), + (140, 'walk', (.16,.25)), + (40, 'set', {}), + (150, 'ramp', {4:.2,5:-1.02,8:.7,10:0}), + (500, 'pan', {}), + (60, 'ramp', {19:1}), + (130, 'lift_pan', {}), + (70, 'ramp', {4:.2,5:-1.55,11:0}), + (430, 'walk', (.18,-.90)), + (40, 'set', {}), + (100, 'ramp', {4:.25,5:-1.25,9:1.57}), + (110, 'ramp', {12:-1.2,13:.05,16:0,17:.25}), + (220, 'ramp', {11:-1.3,5:-1.15}), + (120, 'ramp', {12:-.95,15:.7,17:.3}), + (120, 'ramp', {11:-1.5,5:-1.3,12:-1.15,17:.45}), + (100, 'ramp', {12:-1.5,13:-.3}), + ] + + def walk(self, obs, goal, speed=.22): + p=obs['low_dim_obs'][21:25] + v=np.clip(2*(np.asarray(goal)-p[:2]),-speed,speed) + if self.i==17:v[np.abs(v)<.06]=0 + self.a[:2]=v + self.a[3]=np.clip(-3*p[3],-.4,.4) + + def act(self, obs, tools): + if self.i>=len(self.stages): + self.a[:2]=0;self.a[3]=0 + return self.a.copy() + n,kind,data=self.stages[self.i] + if self.k==0: + self.a[:2]=0;self.a[3]=0 + self.old=self.a.copy();self.dest=self.a.copy() + if kind in ('set','ramp'): + for j,v in data.items():self.dest[j]=v + elif kind=='lift_pan': + self.dest[5]-=.20;self.dest[11]=-.20 + if kind=='set':self.a=self.dest.copy() + if kind in ('ramp','lift_pan'): + self.a=self.old+(self.dest-self.old)*min(1,(self.k+1)/max(1,n-15)) + elif kind=='walk': + self.walk(obs,data,.3 if self.i==1 else (.2 if self.i==10 else .22)) + elif kind=='lift_tool': + self.a[12]-=.003 + # With the wrist rolled, the handle projects as a vertical dark strip. + elif kind=='pan' and self.k%20==0: + im=tools.image('left_wrist');hi=im.max(2);lo=im.min(2) + dark=(hi<105)&((hi.astype(int)-lo.astype(int))<25) + col=dark[5:45].sum(0).astype(float);col[:8]=0 + idx=np.flatnonzero(col>=max(12,col.max()*.75)) + if len(idx): + x=np.average(idx,weights=col[idx]);self.a[5]+=np.clip((x-42)/450,-.04,.04) + else:self.a[5]-=.025 + cycle=self.k//20 + if cycle>=5:self.a[8]+=.02;self.a[5]-=.014 + self.a[5]=np.clip(self.a[5],-1.65,-.7) + self.k+=1 + if self.k>=n:self.k=0;self.i+=1 + return self.a.copy() diff --git a/policies/sandwich_remove/gpt61terra-s1/episodes.csv b/policies/sandwich_remove/gpt61terra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..2870178ebb17fedea06418a056bd8ec94f2f3b5c --- /dev/null +++ b/policies/sandwich_remove/gpt61terra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,3150,timeout,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,3150,timeout,0 +620009,0,3150,timeout,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,0,3150,timeout,0 +620014,0,3150,timeout,0 +620015,0,3150,timeout,0 +620016,0,3150,timeout,0 +620017,0,3150,timeout,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,3150,timeout,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,3150,timeout,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,3150,timeout,0 +620031,0,3150,timeout,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,3150,timeout,0 +620043,0,3150,timeout,0 +620044,0,3150,timeout,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,0,3150,timeout,0 +620048,0,3150,timeout,0 +620049,0,3150,timeout,0 +620050,0,3150,timeout,0 +620051,0,3150,timeout,0 +620052,0,3150,timeout,0 +620053,0,3150,timeout,0 +620054,0,3150,timeout,0 +620055,0,3150,timeout,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,3150,timeout,0 +620059,0,3150,timeout,0 +620060,0,3150,timeout,0 +620061,0,3150,timeout,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,0,3150,timeout,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,3150,timeout,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,3150,timeout,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,3150,timeout,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,0,3150,timeout,0 +620084,0,3150,timeout,0 +620085,0,3150,timeout,0 +620086,0,3150,timeout,0 +620087,0,3150,timeout,0 +620088,0,3150,timeout,0 +620089,0,3150,timeout,0 +620090,0,3150,timeout,0 +620091,0,3150,timeout,0 +620092,0,3150,timeout,0 +620093,0,3150,timeout,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,0,3150,timeout,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/gpt61terra-s1/policy.py b/policies/sandwich_remove/gpt61terra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..7d6800011196addbe4c652dc1e81a25cbce39fc5 --- /dev/null +++ b/policies/sandwich_remove/gpt61terra-s1/policy.py @@ -0,0 +1,43 @@ +"""Deterministic control for the sandwich transfer.""" +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[2] = .74 + a[19] = 0 + a[5:12] = [-1.25, 0, 0, 0, 0, 0, 0] + if 100 <= t < 170: + a[0], a[1] = .2, -.12 + if t >= 230: + a[5:12] = [-1, -.1, 0, .5, 0, 0, 0] + if t >= 330: + a[5:12] = [-.88, -.1, 0, .5, 0, 0, 0] + if t >= 400: + a[4] = .3 + if t >= 500: + a[19] = 1 + if t >= 600: + a[5:12] = [-1.25, -.1, 0, .5, 0, 0, 0] + if 700 <= t < 800: + a[1] = .12 + if t >= 850: + a[5:12] = [-.55, -.1, 0, .5, 0, .5, 0] + if 950 <= t < 1400: + a[1] = -.15 + if t >= 1450: + a[5:12] = [-1.25, -.1, 0, .5, 0, 0, 0] + if 1550 <= t < 1850: + a[1] = .15 + if t >= 1900: + a[5:12] = [-.75, -.1, 0, .5, 0, .5, 0] + if 2000 <= t < 2450: + a[1] = -.15 + if t >= 2500: + a[5:12] = [-1.15, -.1, 0, .5, 0, 0, 0] + a[3] = np.clip(-2 * float(obs['low_dim_obs'][24]), -.7, .7) + return a diff --git a/policies/sandwich_remove/gpt61terra-s2/episodes.csv b/policies/sandwich_remove/gpt61terra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..2870178ebb17fedea06418a056bd8ec94f2f3b5c --- /dev/null +++ b/policies/sandwich_remove/gpt61terra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,3150,timeout,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,3150,timeout,0 +620009,0,3150,timeout,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,0,3150,timeout,0 +620014,0,3150,timeout,0 +620015,0,3150,timeout,0 +620016,0,3150,timeout,0 +620017,0,3150,timeout,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,3150,timeout,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,3150,timeout,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,3150,timeout,0 +620031,0,3150,timeout,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,3150,timeout,0 +620043,0,3150,timeout,0 +620044,0,3150,timeout,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,0,3150,timeout,0 +620048,0,3150,timeout,0 +620049,0,3150,timeout,0 +620050,0,3150,timeout,0 +620051,0,3150,timeout,0 +620052,0,3150,timeout,0 +620053,0,3150,timeout,0 +620054,0,3150,timeout,0 +620055,0,3150,timeout,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,3150,timeout,0 +620059,0,3150,timeout,0 +620060,0,3150,timeout,0 +620061,0,3150,timeout,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,0,3150,timeout,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,3150,timeout,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,3150,timeout,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,3150,timeout,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,0,3150,timeout,0 +620084,0,3150,timeout,0 +620085,0,3150,timeout,0 +620086,0,3150,timeout,0 +620087,0,3150,timeout,0 +620088,0,3150,timeout,0 +620089,0,3150,timeout,0 +620090,0,3150,timeout,0 +620091,0,3150,timeout,0 +620092,0,3150,timeout,0 +620093,0,3150,timeout,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,0,3150,timeout,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/gpt61terra-s2/policy.py b/policies/sandwich_remove/gpt61terra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..c3ff450449e5ec9fdd8cd22ffed22474813c0eae --- /dev/null +++ b/policies/sandwich_remove/gpt61terra-s2/policy.py @@ -0,0 +1,33 @@ +"""A deterministic scripted attempt at the sandwich transfer.""" +import numpy as np + +class Policy: + def reset(self, obs, tools): + self.initial = np.asarray(tools.hold_action(), dtype=np.float32) + self.start_y = float(obs['low_dim_obs'][22]) + + def act(self, obs, tools): + t = int(obs['t']) + a = self.initial.copy() + a[19:21] = 0 + a[5:12] = [-2.6, .2, 0, 0, 0, 0, 0] + a[12:19] = [1.5, -.2, 0, .5, 0, 0, 0] + if 100 <= t < 230: + a[0] = .18 + if t < 180: + a[1] = -.14 + if t >= 350: + a[5:12] = [-1.2, 0, 0, 1, 0, 0, 0] + if t >= 500: + a[19] = 1 + if t >= 650: + a[5:12] = [-1.7, 0, 0, 1, 0, 0, 0] + if t >= 800: + a[5:12] = [-1.7, 0, -1, 1, 0, 0, 0] + if 950 <= t < 1100: + a[1] = -.14 + if t >= 1100: + a[5:12] = [-1.2, 0, -1, 1, 0, 0, 0] + if t >= 1250: + a[19] = 0 + return a diff --git a/policies/sandwich_remove/gpt61terra-s3/episodes.csv b/policies/sandwich_remove/gpt61terra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..df158f99963b08c2d073b3cad7565446154deb5f --- /dev/null +++ b/policies/sandwich_remove/gpt61terra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,3150,timeout,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,3150,timeout,0 +620009,0,3150,timeout,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,769,terminated,0 +620013,0,777,terminated,0 +620014,0,3150,timeout,0 +620015,0,3150,timeout,0 +620016,0,3150,timeout,0 +620017,0,3150,timeout,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,3150,timeout,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,3150,timeout,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,3150,timeout,0 +620031,0,3150,timeout,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,768,terminated,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,3150,timeout,0 +620043,0,3150,timeout,0 +620044,0,3150,timeout,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,0,3150,timeout,0 +620048,0,3150,timeout,0 +620049,0,3150,timeout,0 +620050,0,3150,timeout,0 +620051,0,3150,timeout,0 +620052,0,3150,timeout,0 +620053,0,3150,timeout,0 +620054,0,3150,timeout,0 +620055,0,3150,timeout,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,3150,timeout,0 +620059,0,229,terminated,0 +620060,0,3150,timeout,0 +620061,0,441,terminated,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,0,3150,timeout,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,439,terminated,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,599,terminated,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,3150,timeout,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,766,terminated,0 +620083,0,3150,timeout,0 +620084,0,3150,timeout,0 +620085,0,3150,timeout,0 +620086,0,3150,timeout,0 +620087,0,3150,timeout,0 +620088,0,3150,timeout,0 +620089,0,3150,timeout,0 +620090,0,3150,timeout,0 +620091,0,3150,timeout,0 +620092,0,753,terminated,0 +620093,0,352,terminated,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,0,3150,timeout,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/gpt61terra-s3/policy.py b/policies/sandwich_remove/gpt61terra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..337545c588b10cdb6a62802456ac39ac9dd5956b --- /dev/null +++ b/policies/sandwich_remove/gpt61terra-s3/policy.py @@ -0,0 +1,44 @@ +"""Deterministic two-handed manipulation policy for the pan and spatula.""" +import numpy as np + +class Policy: + def reset(self, obs, tools): + self.initial = np.asarray(tools.hold_action(), dtype=np.float32) + self.x0 = float(obs['low_dim_obs'][21]) + self.y0 = float(obs['low_dim_obs'][22]) + self.phase = 0 + self.since = 0 + + def act(self, obs, tools): + t = int(obs['t']) + q = obs['low_dim_obs'] + a = self.initial.copy() + a[0:2] = 0 + a[2] = .74 + a[3:5] = 0 + a[5:12] = [-1.2, 0, 0, 0, 0, 0, 0] + a[12:19] = [-1.2, 0, 0, 0, 0, 0, 0] + a[19:21] = 0 + if t >= 80 and t < 155: + xerr = self.x0 + .22 - float(q[21]) + if xerr > .015: a[0] = min(.25, max(.06, xerr * 1.3)) + if t >= 210: + a[5:12] = [-.3, 0, -.2, 0, 0, 0, 0] + a[12:19] = [-.4, 0, .15, 1., 0, 0, 0] + if t >= 340: + a[19:21] = 1 + if t >= 430: + a[5] = -.65 + a[12] = -.75 + if t >= 520: + # Move the held pan from the stove toward the board. + target_y = self.y0 - .42 + if q[22] > target_y + .025: + a[1] = -.18 + if t >= 750: + a[9] = .8 + a[5] = -.4 + a[12] = -.45 + if t >= 950: + a[19:21] = 0 + return a diff --git a/policies/sandwich_remove/gpt6sol-s1/episodes.csv b/policies/sandwich_remove/gpt6sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..2870178ebb17fedea06418a056bd8ec94f2f3b5c --- /dev/null +++ b/policies/sandwich_remove/gpt6sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,3150,timeout,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,3150,timeout,0 +620009,0,3150,timeout,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,0,3150,timeout,0 +620014,0,3150,timeout,0 +620015,0,3150,timeout,0 +620016,0,3150,timeout,0 +620017,0,3150,timeout,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,3150,timeout,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,3150,timeout,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,3150,timeout,0 +620031,0,3150,timeout,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,3150,timeout,0 +620043,0,3150,timeout,0 +620044,0,3150,timeout,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,0,3150,timeout,0 +620048,0,3150,timeout,0 +620049,0,3150,timeout,0 +620050,0,3150,timeout,0 +620051,0,3150,timeout,0 +620052,0,3150,timeout,0 +620053,0,3150,timeout,0 +620054,0,3150,timeout,0 +620055,0,3150,timeout,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,3150,timeout,0 +620059,0,3150,timeout,0 +620060,0,3150,timeout,0 +620061,0,3150,timeout,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,0,3150,timeout,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,3150,timeout,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,3150,timeout,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,3150,timeout,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,0,3150,timeout,0 +620084,0,3150,timeout,0 +620085,0,3150,timeout,0 +620086,0,3150,timeout,0 +620087,0,3150,timeout,0 +620088,0,3150,timeout,0 +620089,0,3150,timeout,0 +620090,0,3150,timeout,0 +620091,0,3150,timeout,0 +620092,0,3150,timeout,0 +620093,0,3150,timeout,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,0,3150,timeout,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/gpt6sol-s1/policy.py b/policies/sandwich_remove/gpt6sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..4025d06c11eced0297f9e7336c9231fee2028910 --- /dev/null +++ b/policies/sandwich_remove/gpt6sol-s1/policy.py @@ -0,0 +1,81 @@ +"""Deterministic camera and body based controller for the sandwich task.""" + +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[19] = 0.6 + self.home[20] = 0.6 + self.handle_x = None + + @staticmethod + def _drive(raw, obs, x_target, y_target, yaw_target, gain=2.5): + body = obs["low_dim_obs"] + x, y, yaw = float(body[21]), float(body[22]), float(body[24]) + dx, dy = x_target - x, y_target - y + c, s = np.cos(yaw), np.sin(yaw) + forward = c * dx + s * dy + lateral = -s * dx + c * dy + vx, vy = np.clip(gain * np.array([forward, lateral]), -0.25, 0.25) + if np.hypot(dx, dy) < 0.015: + vx = vy = 0.0 + raw[0], raw[1] = vx, vy + raw[3] = np.clip(3.0 * (yaw_target - yaw), -0.7, 0.7) + + @staticmethod + def _spatula_x(image): + hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) + mask = cv2.inRange(hsv, (5, 120, 50), (22, 255, 255)) + ys, xs = np.where(mask[:35] > 0) + if len(xs) < 20: + return None + threshold = np.percentile(ys, 85) + return float(np.median(xs[ys >= threshold])) + + def act(self, obs, tools): + t = int(obs["t"]) + raw = self.home.copy() + + if t < 180: + self._drive(raw, obs, 0.16, 0.35, 0.0) + return raw + + if t == 180: + self.handle_x = self._spatula_x(tools.image("head")) + + shift = 0.0 + if self.handle_x is not None: + shift = float(np.clip((self.handle_x - 65.0) * 0.012, -0.16, 0.16)) + + if t < 265: + arm = [-0.7, 0.0, -0.5 - shift, 0.0, -0.4, 0.4, 0.0] + grip = 0.6 + elif t < 355: + arm = [-1.3, 0.0, -0.8 - shift, 0.6, -0.4, 0.4, 0.0] + grip = 0.6 + elif t < 440: + arm = [-1.3, 0.0, -0.8 - shift, 0.6, -0.4, 0.4, 0.0] + grip = 1.0 + elif t < 550: + arm = [-1.55, 0.0, -0.8 - shift, 0.6, -0.4, 0.4, 0.0] + grip = 1.0 + elif t < 800: + self._drive(raw, obs, 0.12, 0.04, 0.0, gain=1.8) + arm = [-1.15, 0.0, -0.85 - shift, 0.45, -0.4, 0.35, 0.0] + grip = 1.0 + elif t < 930: + arm = [-1.05, 0.0, -1.15 - shift, 0.25, -0.4, 0.3, 0.0] + grip = 1.0 + elif t < 1010: + arm = [-1.05, 0.0, -1.15 - shift, 0.25, -0.4, 0.3, 0.0] + grip = 0.0 + else: + arm = [-0.5, 0.0, -0.6, 0.0, 0.0, 0.0, 0.0] + grip = 0.0 + + raw[5:12] = arm + raw[19] = grip + return raw diff --git a/policies/sandwich_remove/gpt6sol-s2/episodes.csv b/policies/sandwich_remove/gpt6sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..58f81700f8eb6de593446df1ad52d613fa4d797f --- /dev/null +++ b/policies/sandwich_remove/gpt6sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,3150,timeout,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,3150,timeout,0 +620009,0,3150,timeout,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,0,3150,timeout,0 +620014,0,3150,timeout,0 +620015,0,549,terminated,0 +620016,0,3150,timeout,0 +620017,0,3150,timeout,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,3150,timeout,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,3150,timeout,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,3150,timeout,0 +620031,0,3150,timeout,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,560,terminated,0 +620043,0,3150,timeout,0 +620044,0,3150,timeout,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,0,484,terminated,0 +620048,0,3150,timeout,0 +620049,0,3150,timeout,0 +620050,0,3150,timeout,0 +620051,0,3150,timeout,0 +620052,0,3150,timeout,0 +620053,0,3150,timeout,0 +620054,0,3150,timeout,0 +620055,0,547,terminated,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,3150,timeout,0 +620059,0,3150,timeout,0 +620060,0,544,terminated,0 +620061,0,3150,timeout,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,0,3150,timeout,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,3150,timeout,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,3150,timeout,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,3150,timeout,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,0,3150,timeout,0 +620084,0,3150,timeout,0 +620085,0,3150,timeout,0 +620086,0,3150,timeout,0 +620087,0,3150,timeout,0 +620088,0,3150,timeout,0 +620089,0,3150,timeout,0 +620090,0,3150,timeout,0 +620091,0,482,terminated,0 +620092,0,3150,timeout,0 +620093,0,3150,timeout,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,0,3150,timeout,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/gpt6sol-s2/policy.py b/policies/sandwich_remove/gpt6sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..13360a4a4b860a1e3d950a014facf6d8d5563e6b --- /dev/null +++ b/policies/sandwich_remove/gpt6sol-s2/policy.py @@ -0,0 +1,89 @@ +"""Deterministic upper body controller for the sandwich task.""" + +import math + +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.initial = np.asarray(tools.hold_action(), dtype=np.float32) + + @staticmethod + def _navigate(action, obs, x_target, y_target, speed=0.20): + state = obs["low_dim_obs"] + x, y, yaw = float(state[21]), float(state[22]), float(state[24]) + wx = float(np.clip(2.4 * (x_target - x), -speed, speed)) + wy = float(np.clip(2.4 * (y_target - y), -speed, speed)) + if abs(wx) < 0.07: + wx = 0.0 + if abs(wy) < 0.07: + wy = 0.0 + action[0] = math.cos(yaw) * wx + math.sin(yaw) * wy + action[1] = -math.sin(yaw) * wx + math.cos(yaw) * wy + action[3] = float(np.clip(-1.8 * yaw, -0.45, 0.45)) + + @staticmethod + def _arm(action, shoulder_pitch, shoulder_yaw, wrist_pitch=0.0, + wrist_roll=0.0, elbow=0.0): + action[5:12] = [shoulder_pitch, 0.0, shoulder_yaw, elbow, + wrist_roll, wrist_pitch, 0.0] + + def act(self, obs, tools): + t = int(obs["t"]) + a = self.initial.copy() + a[:5] = [0.0, 0.0, 0.74, 0.0, 0.0] + a[5:19] = 0.0 + a[19:] = [0.0, 0.6] + + if t < 45: + a[0] = 0.25 + elif t < 120: + a[1] = -0.20 + elif t < 200: + a[0] = 0.30 + self._arm(a, -0.60, 0.0) + elif t < 255: + a[0] = 0.30 + a[1] = -0.10 + a[4] = 0.30 + self._arm(a, -0.40, 0.10) + elif t < 315: + a[0] = 0.30 + a[1] = -0.10 + a[4] = 0.30 + self._arm(a, -0.40, 0.10) + a[19] = 1.0 + elif t < 365: + a[4] = 0.30 + self._arm(a, -0.25, 0.10) + a[19] = 1.0 + elif t < 420: + a[4] = 0.60 + self._arm(a, -0.55, 0.25) + a[19] = 1.0 + elif t < 475: + a[2] = 0.70 + a[4] = 0.60 + self._arm(a, -0.55, 0.25, 0.8) + a[19] = 1.0 + elif t < 530: + a[2] = 0.70 + a[4] = 0.60 + self._arm(a, -0.75, 0.25, 0.8) + a[19] = 1.0 + elif t < 800: + a[4] = 0.60 if t < 650 else 0.30 + self._arm(a, -0.75, 0.25, 0.8) + a[19] = 1.0 + self._navigate(a, obs, 0.14, -0.48, 0.25) + elif t < 900: + a[4] = 0.30 + self._arm(a, -0.40, -0.20, 0.0) + a[19] = 1.0 + self._navigate(a, obs, 0.14, -0.48, 0.12) + else: + a[4] = 0.30 + self._arm(a, -0.35, -0.20, 0.3) + a[19] = 0.0 + return a diff --git a/policies/sandwich_remove/gpt6sol-s3/episodes.csv b/policies/sandwich_remove/gpt6sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..576c788a9f4a02ed5af6d7aab8e578138e7fb520 --- /dev/null +++ b/policies/sandwich_remove/gpt6sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,658,terminated,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,659,terminated,0 +620009,0,3150,timeout,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,658,terminated,0 +620013,0,658,terminated,0 +620014,0,3150,timeout,0 +620015,0,3150,timeout,0 +620016,0,3150,timeout,0 +620017,0,3150,timeout,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,3150,timeout,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,3150,timeout,0 +620028,0,658,terminated,0 +620029,0,3150,timeout,0 +620030,0,659,terminated,0 +620031,0,3150,timeout,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,659,terminated,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,658,terminated,0 +620041,0,3150,timeout,0 +620042,0,3150,timeout,0 +620043,0,3150,timeout,0 +620044,0,659,terminated,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,0,3150,timeout,0 +620048,0,660,terminated,0 +620049,0,659,terminated,0 +620050,0,3150,timeout,0 +620051,0,3150,timeout,0 +620052,0,3150,timeout,0 +620053,0,3150,timeout,0 +620054,0,658,terminated,0 +620055,0,3150,timeout,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,3150,timeout,0 +620059,0,3150,timeout,0 +620060,0,3150,timeout,0 +620061,0,3150,timeout,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,441,terminated,0 +620065,0,442,terminated,0 +620066,0,659,terminated,0 +620067,0,3150,timeout,0 +620068,0,660,terminated,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,658,terminated,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,3150,timeout,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,3150,timeout,0 +620080,0,659,terminated,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,0,3150,timeout,0 +620084,0,3150,timeout,0 +620085,0,3150,timeout,0 +620086,0,659,terminated,0 +620087,0,662,terminated,0 +620088,0,3150,timeout,0 +620089,0,3150,timeout,0 +620090,0,440,terminated,0 +620091,0,3150,timeout,0 +620092,0,3150,timeout,0 +620093,0,3150,timeout,0 +620094,0,659,terminated,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,0,3150,timeout,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/gpt6sol-s3/policy.py b/policies/sandwich_remove/gpt6sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..3e4f1030bd060c7439e42a3e0f1fe40e03f60c47 --- /dev/null +++ b/policies/sandwich_remove/gpt6sol-s3/policy.py @@ -0,0 +1,81 @@ +"""Deterministic whole-body controller for the pan-to-board task.""" + +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.step = 0 + + def act(self, obs, tools): + t = self.step + self.step += 1 + pose = np.asarray(obs['low_dim_obs'], dtype=float) + x, y = pose[21:23] + a = np.asarray(tools.hold_action(), dtype=float) + a[0:5] = [0, 0, .74, 0, 0] + a[5:12] = 0 + a[12:19] = 0 + a[19:21] = .6 + + if t < 65: + a[12:19] = [-.5, 0, .5, 0, 0, 0, 0] + elif t < 200: + if x < .33: + a[0] = .16 + a[12:19] = [-.5, 0, .5, 0, 0, 0, 0] + elif t < 260: + a[2] = .82 + a[12:19] = [-.25, 0, .45, 0, 0, 0, 0] + elif t < 330: + a[2] = .82 + a[12:19] = [-.25, 0, .45, 0, 0, 0, 0] + a[20] = 1 + elif t < 430: + a[2] = .82 + a[12:19] = [-.7, 0, .45, 0, 0, 0, 0] + a[20] = 1 + elif t < 520: + a[2] = .82 + a[20] = 1 + elif t < 590: + a[2] = .82 + a[12:19] = [-.3, 0, .8, 0, 0, 0, 0] + a[20] = 1 + elif t < 650: + a[2] = .82 + a[12:19] = [-.5, 0, -.5, 0, 0, 0, 0] + a[20] = 1 + elif t < 740: + a[2] = .82 + a[12:19] = [-.25, 0, .8, 0, 0, 0, 0] + a[20] = 1 + elif t < 850: + a[2] = .82 + yaw = .8 - .34 * (t - 740) / 110 + a[12:19] = [-.25, 0, yaw, 0, 0, 0, 0] + a[20] = 1 + elif t < 960: + a[2] = .68 + a[12:19] = [-.25, 0, .46, 0, 0, 0, 0] + a[20] = 1 + elif t < 1100: + a[2] = .68 + yaw = .46 + .54 * (t - 960) / 140 + a[12:19] = [-.25, 0, yaw, 0, 0, 0, 0] + a[20] = 1 + elif t < 1250: + a[2] = .82 + a[12:19] = [-.75, 0, 1, 0, 0, 0, 0] + a[20] = 1 + elif t < 1650: + a[2] = .82 + a[12:19] = [-.75, 0, 1, 0, 0, 0, 0] + a[20] = 1 + if y > -.35: + a[1] = -.16 + else: + a[2] = .74 + a[12:19] = [-.25, 0, 1, 0, 0, 0, 0] + a[20] = 0 + return a diff --git a/policies/sandwich_remove/kimi31pro-s2/episodes.csv b/policies/sandwich_remove/kimi31pro-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..96eda8dcaf6ce38c789cde921ecb4628084e57d4 --- /dev/null +++ b/policies/sandwich_remove/kimi31pro-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,3150,timeout,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,780,terminated,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,3150,timeout,0 +620009,0,948,terminated,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,0,3150,timeout,0 +620014,0,3150,timeout,0 +620015,0,3150,timeout,0 +620016,0,3150,timeout,0 +620017,0,779,terminated,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,3150,timeout,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,851,terminated,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,3150,timeout,0 +620031,0,3150,timeout,0 +620032,0,455,terminated,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,539,terminated,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,3150,timeout,0 +620043,0,783,terminated,0 +620044,0,3150,timeout,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,0,3150,timeout,0 +620048,0,948,terminated,0 +620049,0,3150,timeout,0 +620050,0,3150,timeout,0 +620051,0,3150,timeout,0 +620052,0,3150,timeout,0 +620053,0,3150,timeout,0 +620054,0,3150,timeout,0 +620055,0,3150,timeout,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,952,terminated,0 +620059,0,3150,timeout,0 +620060,0,947,terminated,0 +620061,0,909,terminated,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,946,terminated,0 +620065,0,3150,timeout,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,3150,timeout,0 +620072,0,946,terminated,0 +620073,0,946,terminated,0 +620074,0,3150,timeout,0 +620075,0,3150,timeout,0 +620076,0,849,terminated,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,946,terminated,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,0,3150,timeout,0 +620084,0,3150,timeout,0 +620085,0,451,terminated,0 +620086,0,3150,timeout,0 +620087,0,3150,timeout,0 +620088,0,3150,timeout,0 +620089,0,3150,timeout,0 +620090,0,954,terminated,0 +620091,0,948,terminated,0 +620092,0,3150,timeout,0 +620093,0,455,terminated,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,0,3150,timeout,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/kimi31pro-s2/policy.py b/policies/sandwich_remove/kimi31pro-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..7a42d0a627aef6a15c71affe886c8e2a4092c407 --- /dev/null +++ b/policies/sandwich_remove/kimi31pro-s2/policy.py @@ -0,0 +1,82 @@ +"""Hand-written control policy for the sandwich transfer task. + +The controller uses timed arm postures with continuous pelvis feedback. It first +acquires the spatula with the left hand, presents the blade to the sandwich, and +then sweeps toward the chopping board. Everything is deterministic and uses only +proprioception and the raw action interface. +""" + +import numpy as np + + +class Policy: + # Arm joint order: shoulder pitch/roll/yaw, elbow, wrist roll/pitch/yaw. + BACK = (0.65, 0.0, 0.0, 0.8, 0.0, 0.0, 0.0) + HIGH = (-1.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0) + REACH = (-1.0, 0.0, 0.0, 0.8, 0.0, 0.0, 0.0) + GRASP = (-0.5, 0.0, 0.0, 0.8, 0.0, 0.0, 0.0) + LIFT = (-1.2, 0.0, 0.0, 0.8, 0.0, 0.0, 0.0) + BLADE = (-0.95, 0.0, 0.0, 0.8, 0.0, 0.0, -0.3) + BLADE_LIFT = (-1.2, 0.0, 0.0, 0.8, 0.0, 0.0, -0.3) + + # end step, base x/y, left-arm posture, left grip, lateral speed limit + STAGES = ( + (55, 0.10, 0.08, BACK, 0.0, 0.16), + (120, 0.10, 0.08, HIGH, 0.0, 0.16), + (310, 0.21, 0.08, HIGH, 0.0, 0.16), + (380, 0.21, 0.08, HIGH, 0.0, 0.16), + (435, 0.21, 0.08, REACH, 0.0, 0.16), + (500, 0.21, 0.08, GRASP, 0.0, 0.16), + (560, 0.21, 0.08, GRASP, 1.0, 0.16), + (640, 0.21, 0.08, LIFT, 1.0, 0.16), + (750, 0.08, 0.08, LIFT, 1.0, 0.16), + (830, 0.14, 0.08, BLADE, 1.0, 0.16), + (940, 0.20, 0.08, BLADE, 1.0, 0.16), + (1010, 0.20, -0.45, BLADE, 1.0, 0.65), + (1090, 0.20, -0.45, BLADE_LIFT, 1.0, 0.16), + ) + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + + @staticmethod + def _base_speed(error, limit): + command = float(np.clip(4.0 * error, -limit, limit)) + if abs(error) < 0.008: + return 0.0 + if abs(command) < 0.065: + return float(np.copysign(0.065, command)) + return command + + def act(self, obs, tools): + t = int(obs["t"]) + stage = self.STAGES[-1] + for candidate in self.STAGES: + if t < candidate[0]: + stage = candidate + break + _, target_x, target_y, arm, left_grip, lateral_limit = stage + + raw = self.hold.copy() + raw[2] = 0.74 + raw[4] = 0.0 + raw[5:12] = arm + raw[12:19] = self.BACK + raw[19] = left_grip + raw[20] = 0.0 + + pelvis = obs["low_dim_obs"][21:25] + dx = target_x - pelvis[0] + dy = target_y - pelvis[1] + c, s = np.cos(pelvis[3]), np.sin(pelvis[3]) + forward_error = c * dx + s * dy + lateral_error = -s * dx + c * dy + raw[0] = self._base_speed(forward_error, 0.20) + raw[1] = self._base_speed(lateral_error, lateral_limit) + yaw_error = -pelvis[3] + raw[3] = ( + float(np.clip(1.2 * yaw_error, -0.3, 0.3)) + if abs(yaw_error) > 0.025 + else 0.0 + ) + return raw diff --git a/policies/sandwich_remove/opus-s1/episodes.csv b/policies/sandwich_remove/opus-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..0a73bfde88d1f1c424158e34eae7a99180892a48 --- /dev/null +++ b/policies/sandwich_remove/opus-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,3150,timeout,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,3150,timeout,0 +620009,0,3150,timeout,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,0,3150,timeout,0 +620014,0,3150,timeout,0 +620015,0,3150,timeout,0 +620016,0,3150,timeout,0 +620017,0,3150,timeout,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,3150,timeout,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,2930,terminated,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,3150,timeout,0 +620031,0,3150,timeout,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,3150,timeout,0 +620043,0,3150,timeout,0 +620044,0,3150,timeout,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,0,3150,timeout,0 +620048,0,3150,timeout,0 +620049,0,3150,timeout,0 +620050,0,1186,terminated,0 +620051,0,3150,timeout,0 +620052,0,3150,timeout,0 +620053,0,3150,timeout,0 +620054,0,3150,timeout,0 +620055,0,3150,timeout,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,1793,terminated,0 +620059,0,3150,timeout,0 +620060,0,3150,timeout,0 +620061,0,3150,timeout,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,0,1180,terminated,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,3150,timeout,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,3150,timeout,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,3150,timeout,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,0,3150,timeout,0 +620084,0,3150,timeout,0 +620085,0,3150,timeout,0 +620086,0,3150,timeout,0 +620087,0,3150,timeout,0 +620088,0,3150,timeout,0 +620089,0,3150,timeout,0 +620090,0,3150,timeout,0 +620091,0,3150,timeout,0 +620092,0,3150,timeout,0 +620093,0,3150,timeout,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,0,3150,timeout,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/opus-s1/policy.py b/policies/sandwich_remove/opus-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..8980b418d72e5dc73c92648ad366f889f0326742 --- /dev/null +++ b/policies/sandwich_remove/opus-s1/policy.py @@ -0,0 +1,1452 @@ +"""Scripted policy for the G1 sandwich_remove task. + +The robot walks to the stove, takes the spatula in its right hand, picks the frying +pan up by its handle with the left hand, walks to the chopping board, tips the pan over +the board and pushes the sandwich out with the spatula. + +Everything is hand-written: forward kinematics from the G1 model geometry, a small +damped-least-squares IK, colour segmentation of the robot's cameras and a phase script. +""" + +import cv2 +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 _quat(w, x, y, z): + q = np.array([w, x, y, z]) / np.linalg.norm([w, x, y, z]) + w, x, y, z = q + return np.array([ + [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]]) + + +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 + + +_SH_Q = {s: _quat(0.990264, s * 0.139201, 1.38722e-05, -s * 9.7255e-05) for s in (1, -1)} +_RO_Q = {s: _quat(0.990268, -s * 0.139172, 0, 0) for s in (1, -1)} + + +def torso_T(waist): + """Pelvis -> torso_link for waist (yaw, roll, pitch).""" + M = _T(_rz(waist[0])) + M = M @ _T(_rx(waist[1]), (-0.0039635, 0, 0.035)) + return M @ _T(_ry(waist[2]), (0, 0, 0.019)) + + +def arm_T(q, side, tool=0.15): + """Torso -> tool frame (tool metres along the wrist_yaw x axis). side +1 left, -1 right.""" + s = side + M = _T(_SH_Q[s], (0.0039563, s * 0.10022, 0.24778)) @ _T(_ry(q[0])) + M = M @ _T(_RO_Q[s], (0, s * 0.038, -0.013831)) @ _T(_rx(q[1])) + M = M @ _T(None, (0, s * 0.00624, -0.1032)) @ _T(_rz(q[2])) + M = M @ _T(None, (0.015783, 0, -0.080518)) @ _T(_ry(q[3])) + M = M @ _T(None, (0.1, s * 0.00188791, -0.01)) @ _T(_rx(q[4])) + M = M @ _T(None, (0.038, 0, 0)) @ _T(_ry(q[5])) + M = M @ _T(None, (0.046, 0, 0)) @ _T(_rz(q[6])) + return M @ _T(None, (tool, 0, 0)) + + +QLO = np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]) +QHI = np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]) + + +def ik(pos, side, q0, waist=(0, 0, 0), tool=0.15, axis=None, axis_w=0.3, side_axis=None, + side_w=0.2, q_w=0.02, iters=60): + """Damped least-squares IK. pos: tool point in the pelvis frame. axis: desired gripper + pointing direction (tool x axis); side_axis: desired tool y axis (finger opening line).""" + q = np.clip(np.asarray(q0, float), QLO + 1e-3, QHI - 1e-3) + qref = q.copy() + Tw = torso_T(waist) + + def resid(q): + M = Tw @ arm_T(q, side, tool) + r = [M[:3, 3] - pos] + if axis is not None: + r.append(axis_w * (M[:3, 0] - axis / np.linalg.norm(axis))) + if side_axis is not None: + r.append(side_w * (M[:3, 1] - side_axis / np.linalg.norm(side_axis))) + r.append(q_w * (q - qref)) + return np.concatenate(r) + + lam = 1e-3 + r = resid(q) + for _ in range(iters): + J = np.zeros((len(r), 7)) + for j in range(7): + dq = np.zeros(7) + dq[j] = 1e-5 + J[:, j] = (resid(q + dq) - r) / 1e-5 + step = np.linalg.solve(J.T @ J + lam * np.eye(7), -J.T @ r) + qn = np.clip(q + step, QLO, QHI) + rn = resid(qn) + if rn @ rn < r @ r: + q, r = qn, rn + lam = max(lam * 0.5, 1e-6) + if np.linalg.norm(step) < 1e-5: + break + else: + lam *= 4 + if lam > 1e3: + break + M = Tw @ arm_T(q, side, tool) + return q, float(np.linalg.norm(M[:3, 3] - pos)) + + +# Head camera, fitted to images of the arm (torso_link frame; looks along its +x). +CAM_P = np.array([0.177, 0.0146, 0.359]) +CAM_PITCH = 1.171 +CAM_FOVY = 68.75 + + +def head_cam_T(ld): + W = _T(_rz(ld[24]), ld[21:24]) + return W @ torso_T(ld[0:3]) @ _T(_ry(CAM_PITCH), CAM_P) + + +def pix_to_plane(ld, u, v, z, W=84): + f = (W / 2) / np.tan(np.radians(CAM_FOVY) / 2) + d = np.array([1.0, (W / 2 - u) / f, (W / 2 - v) / f]) + M = head_cam_T(ld) + o, d = M[:3, 3], M[:3, :3] @ d + t = (z - o[2]) / d[2] + return o + t * d + + +def wrap(a): + return (a + np.pi) % (2 * np.pi) - np.pi + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# Fixed IK restart seeds (left-arm convention; mirrored for the right arm). +IK_SEEDS = [ + np.array([-1.0, 0.3, 0.0, 0.8, 0.0, 0.0, 0.0]), + np.array([-0.5, 0.2, 0.0, 1.2, 0.0, -0.8, 0.0]), + np.array([-1.5, 0.2, 0.3, 1.4, 1.5, -1.2, 0.3]), + np.array([-1.3, 0.0, -0.6, 1.4, -1.0, 0.6, -1.0]), + np.array([-0.3, 0.6, 0.6, 0.5, 0.8, 0.5, 0.5]), + np.array([-2.0, 0.1, -1.5, 1.3, -0.8, 0.6, -1.5]), + np.array([-0.8, 0.5, 1.0, 1.0, -1.2, -0.5, 0.8]), + np.array([-1.2, 0.8, 0.5, 0.2, 1.0, 1.0, -0.5]), + np.array([0.0, 0.3, 0.0, 1.5, 0.0, 0.0, 0.0]), + np.array([-1.8, 0.5, 0.0, 0.0, 0.0, 1.2, 0.0]), +] + + +# ----------------------------------------------------------------------------- perception +def plane_pts(ld, us, vs, z, W=84): + """Head-camera pixels -> points on the horizontal plane at height z (world).""" + f = (W / 2) / np.tan(np.radians(CAM_FOVY) / 2) + M = head_cam_T(ld) + d = np.stack([np.ones_like(us, float), (W / 2 - us) / f, (W / 2 - vs) / f], 1) @ M[:3, :3].T + t = (z - M[2, 3]) / d[:, 2] + return M[:3, 3] + t[:, None] * d + + +def _largest(mask): + n, lab, stats, _ = cv2.connectedComponentsWithStats(mask.astype(np.uint8), connectivity=8) + if n <= 1: + return mask.astype(bool) + k = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + return lab == k + + +def find_handle(im, ld, z=0.93): + """Frying-pan handle: thin dark structure reaching furthest to +y (the loop end).""" + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + dark = (hsv[..., 2] < 75).astype(np.uint8) + big = cv2.morphologyEx(dark, cv2.MORPH_OPEN, np.ones((5, 5), np.uint8)) + big = cv2.dilate(big, np.ones((3, 3), np.uint8)) + thin = dark & (1 - big) + n, lab, stats, _ = cv2.connectedComponentsWithStats(thin, connectivity=8) + best = None + for k in range(1, n): + if stats[k, cv2.CC_STAT_AREA] < 6: + continue + vs, us = np.nonzero(lab == k) + Wp = plane_pts(ld, us + 0.5, vs + 0.5, z) + score = Wp[:, 1].max() + if best is None or score > best[0]: + best = (score, Wp) + if best is None: + return None + Wp = best[1] + c = Wp.mean(0) + _, _, vt = np.linalg.svd(Wp[:, :2] - c[:2]) + d = vt[0] if vt[0][1] > 0 else -vt[0] + s = (Wp[:, :2] - c[:2]) @ d + return dict(n=len(Wp), center=c, dir=d, end=c[:2] + d * s.max(), root=c[:2] + d * s.min()) + + +def find_spatula(im, ld, z=0.95): + """Orange spatula: centroid, axis (pointing to the handle end, towards the robot) and handle end.""" + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(int) + m = (hsv[..., 0] >= 5) & (hsv[..., 0] <= 18) & (hsv[..., 1] > 150) & (hsv[..., 2] > 80) + if m.sum() < 8: + return None + m = _largest(m) + vs, us = np.nonzero(m) + Wp = plane_pts(ld, us + 0.5, vs + 0.5, z) + c = Wp.mean(0) + _, _, vt = np.linalg.svd(Wp[:, :2] - c[:2]) + d = vt[0] if vt[0][0] < 0 else -vt[0] + s = (Wp[:, :2] - c[:2]) @ d + end = c[:2] + d * s.max() + return dict(n=len(us), center=c, dir=d, end=end) + + +def find_sandwich(im, ld, z=0.96): + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(int) + m = (hsv[..., 0] >= 20) & (hsv[..., 0] <= 35) & (hsv[..., 1] > 100) & (hsv[..., 2] > 120) + if m.sum() < 8: + return None + m = _largest(m) + vs, us = np.nonzero(m) + Wp = plane_pts(ld, us + 0.5, vs + 0.5, z) + return dict(n=len(us), center=Wp.mean(0)) + + +def find_board(im, ld, z=0.95): + """Chopping board: light-wood pixels, largest blob, centre on the board plane.""" + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(int) + m = ((hsv[..., 0] >= 8) & (hsv[..., 0] <= 32) & (hsv[..., 1] >= 45) & (hsv[..., 1] <= 170) + & (hsv[..., 2] > 150)) + if m.sum() < 30: + return None + m = _largest(m) + vs, us = np.nonzero(m) + Wp = plane_pts(ld, us + 0.5, vs + 0.5, z) + lo, hi = np.percentile(Wp[:, :2], 3, axis=0), np.percentile(Wp[:, :2], 97, axis=0) + return dict(n=len(us), center=0.5 * (lo + hi), lo=lo, hi=hi) + + +def sandwich_rect(im, ld, z=0.96): + """Sandwich footprint as a rotated rectangle on the plane z (centre, size, corners).""" + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(int) + m = (hsv[..., 0] >= 15) & (hsv[..., 0] <= 35) & (hsv[..., 1] > 90) & (hsv[..., 2] > 90) + if m.sum() < 15: + return None + # keep every sizeable blob: the spatula lying across the sandwich splits its mask + n, lab, stats, _ = cv2.connectedComponentsWithStats(m.astype(np.uint8), connectivity=8) + keep = [k for k in range(1, n) if stats[k, cv2.CC_STAT_AREA] >= 6] + m = np.isin(lab, keep) + vs, us = np.nonzero(m) + Wp = plane_pts(ld, us + 0.5, vs + 0.5, z) + rect = cv2.minAreaRect((Wp[:, :2] * 1000).astype(np.float32)) + (cx, cy), (w, h), ang = rect + return dict(center=np.array([cx, cy]) / 1000, size=(w / 1000, h / 1000), ang=ang, + box=cv2.boxPoints(rect).astype(float) / 1000.0, n=len(us)) + + +# ----------------------------------------------------------------------------- policy +def _unit(v): + v = np.asarray(v, float) + return v / np.linalg.norm(v) + + +def _rodrigues(axis, ang): + k = _unit(axis) + K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]]) + return np.eye(3) + np.sin(ang) * K + (1 - np.cos(ang)) * K @ K + + +class Policy: + """Phase script driven by a generator; act() advances it one control step. + + The script sets base goals, world-frame hand targets and gripper commands; act() + turns hand targets into joint targets with IK every step (so the hands stay put in + the world while the base wobbles) and keeps the base on its goal. + """ + + def reset(self, obs, tools): + self.tools = tools + self.obs = obs + self.a = np.asarray(tools.hold_action(), dtype=np.float64).copy() + self.a[2] = 0.74 + self.a[4] = 0.0 + self.tgt = {1: None, -1: None} + self.base_goal = None + self.walking = False + self.phase = 'start' + self.log = [] + self.info = {} + self.snaps = [] + self.FINGER_SIGN = {1: 1.0, -1: 1.0} + self.gen = self.script() + + # -- state ----------------------------------------------------------------------- + @property + def ld(self): + return self.obs['low_dim_obs'] + + def pose(self): + return self.ld[21:25] + + def world_T(self): + return _T(_rz(self.ld[24]), self.ld[21:24]) + + def to_pelvis(self, p): + p = np.asarray(p, float) + c, s = np.cos(self.ld[24]), np.sin(self.ld[24]) + d = p - self.ld[21:24] + return np.array([c * d[0] + s * d[1], -s * d[0] + c * d[1], d[2]]) + + def vec_to_pelvis(self, v): + c, s = np.cos(self.ld[24]), np.sin(self.ld[24]) + return np.array([c * v[0] + s * v[1], -s * v[0] + c * v[1], v[2]]) + + def hand_T(self, side, tool=0.15, q=None): + if q is None: + q = self.ld[3:10] if side > 0 else self.ld[12:19] + return self.world_T() @ torso_T(self.ld[0:3]) @ arm_T(q, side, tool) + + def qcmd(self, side): + return self.a[5:12] if side > 0 else self.a[12:19] + + def set_q(self, side, q): + if side > 0: + self.a[5:12] = q + else: + self.a[12:19] = q + + # -- low level each step --------------------------------------------------------- + def apply_targets(self): + for side in (1, -1): + t = self.tgt[side] + if t is None: + continue + if t.get('rel'): + pp, ax, sa = t['p'], t.get('ax'), t.get('sa') + else: + pp = self.to_pelvis(t['p']) + ax = None if t.get('ax') is None else self.vec_to_pelvis(t['ax']) + sa = None if t.get('sa') is None else self.vec_to_pelvis(t['sa']) + q, err = ik(pp, side, self.qcmd(side), waist=self.ld[0:3], tool=t.get('tool', 0.15), + axis=ax, side_axis=sa, axis_w=t.get('axw', 0.3), side_w=t.get('saw', 0.2), + q_w=0.005, iters=t.get('iters', 12)) + self.set_q(side, q) + t['err'] = err + + def apply_base(self): + if self.base_goal is None or self.walking: + return + x, y, yaw = self.base_goal + p = self.pose() + dx, dy = x - p[0], y - p[1] + c, s = np.cos(p[3]), np.sin(p[3]) + bx, by = c * dx + s * dy, -s * dx + c * dy + d = np.hypot(bx, by) + if d > 0.035: + v = 0.07 + self.a[0], self.a[1] = v * bx / d, v * by / d + elif d < 0.015: + self.a[0] = self.a[1] = 0.0 + e = wrap(yaw - p[3]) + if abs(e) > 0.04: + self.a[3] = float(np.clip(1.2 * e, -0.3, 0.3)) + if abs(self.a[3]) < 0.08: + self.a[3] = 0.08 * np.sign(e) + elif abs(e) < 0.015: + self.a[3] = 0.0 + + # -- script primitives (generators) --------------------------------------------- + def wait(self, n): + for _ in range(n): + yield + + def walk_to(self, x, y, yaw=0.0, tol=0.02, max_steps=500, vmax=0.3): + self.walking = True + for _ in range(max_steps): + p = self.pose() + dx, dy = x - p[0], y - p[1] + c, s = np.cos(p[3]), np.sin(p[3]) + bx, by = c * dx + s * dy, -s * dx + c * dy + d = np.hypot(bx, by) + e = wrap(yaw - p[3]) + if d < tol and abs(e) < 0.03: + break + v = float(np.clip(1.5 * d, 0.07, vmax)) + if d > tol: + self.a[0], self.a[1] = v * bx / d, v * by / d + else: + self.a[0] = self.a[1] = 0.0 + w = float(np.clip(1.5 * e, -0.5, 0.5)) + self.a[3] = w if abs(e) > 0.03 else 0.0 + if 0 < abs(self.a[3]) < 0.08: + self.a[3] = 0.08 * np.sign(e) + yield + self.a[0] = self.a[1] = self.a[3] = 0.0 + self.walking = False + self.base_goal = (x, y, yaw) + + def move_arms(self, qL=None, qR=None, n=40, gL=None, gR=None): + """Joint-space interpolation (clears world targets of the moved arms).""" + if qL is not None: + self.tgt[1] = None + if qR is not None: + self.tgt[-1] = None + L0, R0 = self.a[5:12].copy(), self.a[12:19].copy() + gL0, gR0 = self.a[19], self.a[20] + for k in range(1, n + 1): + t = k / n + t = t * t * (3 - 2 * t) + if qL is not None: + self.a[5:12] = L0 + t * (np.asarray(qL) - L0) + if qR is not None: + self.a[12:19] = R0 + t * (np.asarray(qR) - R0) + if gL is not None: + self.a[19] = gL0 + t * (gL - gL0) + if gR is not None: + self.a[20] = gR0 + t * (gR - gR0) + yield + + def grip(self, side, g, n=25): + i = 19 if side > 0 else 20 + g0 = self.a[i] + for k in range(1, n + 1): + self.a[i] = g0 + (g - g0) * k / n + yield + + def move_hand(self, side, p, ax=None, sa=None, n=40, tool=0.15, **kw): + """Move a hand target in the world frame along a straight line.""" + if self.tgt[side] is None: + T0 = self.hand_T(side, tool, self.qcmd(side)) + p0, ax0, sa0 = T0[:3, 3], T0[:3, 0], T0[:3, 1] + else: + t0 = self.tgt[side] + p0, ax0, sa0 = t0['p'], t0.get('ax'), t0.get('sa') + if ax0 is None or sa0 is None: + T0 = self.hand_T(side, tool, self.qcmd(side)) + ax0 = T0[:3, 0] if ax0 is None else ax0 + sa0 = T0[:3, 1] if sa0 is None else sa0 + p = np.asarray(p, float) + for k in range(1, n + 1): + t = k / n + t = t * t * (3 - 2 * t) + tg = dict(p=p0 + t * (p - p0), tool=tool, **kw) + if ax is not None: + tg['ax'] = _unit(ax0 + t * (_unit(ax) - ax0)) + if sa is not None: + tg['sa'] = _unit(sa0 + t * (_unit(sa) - sa0)) + self.tgt[side] = tg + yield + self.tgt[side]['iters'] = kw.get('iters', 12) + + def solve_global(self, side, p, ax, sa, tool=0.17): + """Multi-start IK for a world pose (deterministic seeds); returns joint targets.""" + pp = self.to_pelvis(p) + axp, sap = self.vec_to_pelvis(_unit(ax)), self.vec_to_pelvis(_unit(sa)) + waist = self.ld[0:3] + best = None + for q0 in [self.qcmd(side).copy()] + [s * np.array([1, side, side, 1, side, 1, side]) for s in IK_SEEDS]: + q, err = ik(pp, side, q0, waist=waist, tool=tool, axis=axp, side_axis=sap, q_w=0.0, iters=40) + M = torso_T(waist) @ arm_T(q, side, tool) + c = err + 0.3 * np.linalg.norm(M[:3, 0] - axp) + 0.2 * np.linalg.norm(M[:3, 1] - sap) + if best is None or c < best[0] - 1e-4: + best = (c, q, err) + if c < 0.004: + break + return best[1], best[2] + + def reach(self, side, p, ax, sa, tool=0.17, n=50): + """Joint-space move to a globally solved pose, then hold it with Cartesian tracking.""" + q, err = self.solve_global(side, p, ax, sa, tool) + self.info['reach_err'] = err + if side > 0: + yield from self.move_arms(qL=q, n=n) + else: + yield from self.move_arms(qR=q, n=n) + self.tgt[side] = dict(p=np.asarray(p, float), ax=_unit(ax), sa=_unit(sa), tool=tool) + + def safe_move(self, side, p, ax, sa, tool=0.15, z_safe=1.15, n=40): + """Lift (or reorient near the body), traverse at z_safe, then descend to p.""" + if self.tgt[side] is None: + T0 = self.hand_T(side, tool, self.qcmd(side)) + cur = T0[:3, 3] + else: + cur = self.tgt[side]['p'] + up = np.array([cur[0], cur[1], max(cur[2], z_safe)]) + yield from self.move_hand(side, up, ax, sa, n=n, tool=tool) + yield from self.move_hand(side, np.array([p[0], p[1], max(p[2], z_safe)]), ax, sa, n=n, tool=tool) + yield from self.move_hand(side, p, ax, sa, n=n, tool=tool) + + def descend_until_contact(self, side, z_min, ax, sa, tool=0.17, rate=0.0025, sag_thr=0.035): + """Lower the hand target until the measured hand stops following (contact).""" + t = self.tgt[side] + p = np.array(t['p'], float) + base_sag = None + k = 0 + while p[2] > z_min: + p = p - np.array([0, 0, rate]) + self.tgt[side] = dict(p=p.copy(), ax=_unit(ax), sa=_unit(sa), tool=tool) + yield + k += 1 + meas = self.hand_T(side, tool)[:3, 3] + sag = meas[2] - p[2] + if k == 8: + base_sag = sag + if base_sag is not None and sag - base_sag > sag_thr - 0.015: + self.info['contact_z'] = float(meas[2]) + break + self.info['contact_p'] = self.hand_T(side, tool)[:3, 3].copy() + + def set_phase(self, name): + self.phase = name + self.log.append((int(self.obs['t']), name)) + + # -- script ---------------------------------------------------------------------- + TUCK_L = np.array([-0.2, 0.25, 0, -0.9, 0, 0, 0]) + TUCK_R = np.array([-0.2, -0.25, 0, -0.9, 0, 0, 0]) + STANCE = (0.40, 0.50, -0.5) + + SIDE = (0.66, 0.70, -np.pi / 2) + + # stance relative to the sandwich (pan) seen from the look pose: (dx, dy, yaw) + STANCE_REL = (-0.28, 0.32, -0.45) + LOOK = (0.16, 0.22, 0.0) + LOOK_B = (0.15, -0.58, 0.0) + USE_SPATULA = False + + def look_at(self, fn, n=4): + self.a[2], self.a[4] = 0.95, -0.2 + yield from self.wait(40) + rs = [] + for _ in range(n): + r = fn(self.tools.image('head'), self.ld.copy()) + if r is not None: + rs.append(r['center'][:2]) + yield from self.wait(3) + self.a[2], self.a[4] = 0.74, 0.0 + yield from self.wait(20) + self._look = np.mean(rs, 0) if rs else None + + FRONT_REL = (-0.36, 0.03, 0.0) # stance relative to the sandwich for the grasps + + def script(self): + self.set_phase('look') + yield from self.move_arms(qL=self.TUCK_L, qR=self.TUCK_R, n=30) + yield from self.walk_to(*self.LOOK_B) + yield from self.look_at(find_board) + self.dbg('look_board') + self.info['board'] = self._look if self._look is not None else np.array([0.62, -0.60]) + yield from self.walk_to(*self.LOOK) + yield from self.look_at(find_sandwich) + ref = self._look if self._look is not None else np.array([0.70, 0.21]) + self.info['ref0'] = ref + self.set_phase('walk_pan') + yield from self.walk_to(ref[0] + self.FRONT_REL[0], ref[1] + self.FRONT_REL[1], self.FRONT_REL[2]) + self.a[4] = -0.2 + yield from self.wait(30) + self.set_phase('perceive') + yield from self.perceive() + self.a[4] = 0.0 + if self.USE_SPATULA: + self.set_phase('spatula') + yield from self.spatula_grasp() + self.set_phase('sandwich') + yield from self.sandwich_grasp() + if not self.info.get('sw_ok'): + self.set_phase('end') + while True: + yield + self.set_phase('carry') + yield from self.carry_sandwich() + self.set_phase('end') + while True: + yield + + def perceive(self): + """Average a few head-camera detections of handle, spatula and sandwich.""" + acc = {'handle': [], 'spatula': [], 'sandwich': []} + for _ in range(5): + im = self.tools.image('head') + ld = self.ld.copy() + for k, fn in (('handle', find_handle), ('spatula', find_spatula), ('sandwich', find_sandwich)): + r = fn(im, ld) + if r is not None: + acc[k].append(r) + yield from self.wait(4) + for k, rs in acc.items(): + if rs: + self.info[k] = {f: np.mean([r[f] for r in rs], 0) for f in rs[0] if f != 'n'} + else: + self.info[k] = None + + def approach_until_contact(self, side, direction, dist, tool=0.17, rate=0.0012, thr=0.012): + """Advance the hand target along `direction`; stop when the hand stops following.""" + t = self.tgt[side] + p = np.array(t['p'], float) + u = _unit(direction) + base, hits = None, 0 + self.info['contact'] = False + for k in range(int(dist / rate)): + p = p + u * rate + self.tgt[side] = dict(p=p.copy(), ax=t['ax'], sa=t['sa'], tool=tool) + yield + lag = (p - self.hand_T(side, tool)[:3, 3]) @ u + if k == 35: + base = lag + hits = hits + 1 if (base is not None and lag - base > thr) else 0 + if hits >= 3: + self.info['contact'] = True + break + self.info['contact_p'] = self.hand_T(side, tool)[:3, 3].copy() + + def approach_servo(self, side, mask_fn, dist, rate=0.0012, thr=0.012, k_p=1.0 / 1500, every=20): + """Advance along the gripper axis until contact, re-centring the object in the + wrist camera along the finger line every few steps.""" + cam = 'left_wrist' if side > 0 else 'right_wrist' + t = self.tgt[side] + ax, sa, tool = t['ax'], t['sa'], t.get('tool', 0.17) + p = np.array(t['p'], float) + base, hits, lat = None, 0, 0.0 + us = [] + self.info['contact'] = False + for k in range(int(dist / rate)): + if k % every == every - 1: + m = mask_fn(self.tools.image(cam)) + cnt = m.sum(1) + rows = (cnt >= 2) & (cnt <= 40) + if rows.sum() >= 4: + u = float(np.nonzero(m[rows])[1].mean()) + us.append(round(u, 1)) + lat = float(np.clip(-(u - self.WRIST_U0) * k_p, -0.008, 0.008)) / every + else: + lat = 0.0 + p = p + ax * rate + sa * lat + self.tgt[side] = dict(p=p.copy(), ax=ax, sa=sa, tool=tool) + yield + lag = (p - self.hand_T(side, tool)[:3, 3]) @ ax + if k == 35: + base = lag + hits = hits + 1 if (base is not None and lag - base > thr) else 0 + if hits >= 3: + self.info['contact'] = True + break + self.info.setdefault('approach_u', []).append(us) + self.info['contact_p'] = self.hand_T(side, tool)[:3, 3].copy() + + def holding(self, side): + f = self.ld[10:12] if side > 0 else self.ld[19:21] + return float(np.max(f)) > -0.0185 + + def dbg(self, tag): + if getattr(self, 'debug', False): + self.snaps.append((tag, int(self.obs['t']), [self.tools.image(c) for c in ('head', 'left_wrist', 'right_wrist')])) + + @staticmethod + def orange_mask(im): + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(int) + return (hsv[..., 0] >= 5) & (hsv[..., 0] <= 18) & (hsv[..., 1] > 150) & (hsv[..., 2] > 60) + + @staticmethod + def dark_mask(im): + return cv2.cvtColor(im, cv2.COLOR_RGB2HSV)[..., 2] < 60 + + WRIST_U0 = 42.0 # wrist-camera column of the finger gap + WRIST_GAIN = 600.0 # wrist-camera pixels per metre of hand motion along the finger line + + PRE_U0 = 28.0 + + def wrist_center(self, side, ax, sa, mask_fn, iters=6, max_off=0.05, u0=None): + """Shift the hand along its finger line until the object is centred in the wrist camera. + + The image-to-hand gain (and its sign) is estimated online from the observed + response (secant method), starting with a small probing step. + """ + cam = 'left_wrist' if side > 0 else 'right_wrist' + tool = self.tgt[side].get('tool', 0.17) + p0 = self.tgt[side]['p'].copy() + off, gain = 0.0, self.WRIST_GAIN # prior: u increases when moving along +sa + prev = None + us = [] + u0 = self.WRIST_U0 if u0 is None else u0 + for _ in range(iters): + m = mask_fn(self.tools.image(cam)) + cnt = m.sum(1) + rows = (cnt >= 2) & (cnt <= 30) # narrow runs only (not large dark areas) + if rows.sum() < 5: + break + u = float(np.nonzero(m[rows])[1].mean()) + us.append(round(u, 1)) + if prev is not None and abs(off - prev[0]) > 1e-3: + g_est = (u - prev[1]) / (off - prev[0]) + if abs(g_est) > 150: + gain = float(np.clip(g_est, -4000, 4000)) + if abs(u - u0) < 1.5: + break + step = float(np.clip(-(u - u0) / gain, -0.012, 0.012)) + prev = (off, u) + off = float(np.clip(off + step, -max_off, max_off)) + yield from self.move_hand(side, p0 + sa * off, ax, sa, n=15, tool=tool) + yield from self.wait(15) + self.info.setdefault('wrist_u', []).append((side, us, round(gain))) + + # spatula grasp: grip point this far in from the handle end + SPAT_IN = 0.025 + + def spatula_grasp(self): + sp = self.info.get('spatula') + if sp is None: + return + d = _unit([sp['dir'][0], sp['dir'][1], 0.0]) # along the spatula towards its handle end + g = np.array([sp['end'][0], sp['end'][1], 0.98]) - d * self.SPAT_IN + ax = _unit(-d * 0.4 + np.array([0, 0, -1.0])) # tilted towards the blade + sa = _unit(np.cross(ax, d)) # finger line across the handle + for attempt in range(3): + yield from self.grip(-1, 0.0, 10) + yield from self.reach(-1, g + np.array([0, 0, 0.10]), ax, sa, tool=0.17, n=50) + yield from self.wait(15) + yield from self.wrist_center(-1, ax, sa, self.orange_mask) + self.dbg('spat_above') + yield from self.approach_until_contact(-1, np.array([0, 0, -1.0]), 0.16) + self.dbg('spat_contact') + p = self.hand_T(-1, 0.17)[:3, 3] + self.tgt[-1] = dict(p=p + np.array([0, 0, 0.008]), ax=ax, sa=sa, tool=0.17) + yield from self.wait(5) + yield from self.grip(-1, 1.0, 25) + yield from self.wait(30) + self.dbg('spat_closed') + if self.holding(-1): + break + self.info['spat_ok'] = self.holding(-1) + yield from self.move_hand(-1, self.tgt[-1]['p'] + np.array([0, 0, 0.10]), ax, sa, n=40, tool=0.17) + # park the spatula to the right, out of the way of the pan + park = self.world_T() @ np.array([0.30, -0.30, 0.30, 1.0]) + yield from self.move_hand(-1, park[:3], ax, sa, n=50, tool=0.17) + + PAN_FROM_END = 0.11 # left grasp point distance from the handle's loop end + LIFT = 0.03 + PAN_Z = 0.95 # first guess of the handle height at the grasp point + PAN_AX = np.array([1.0, 0, 0]) + + def grasp_across(self, side, g, ax, sa, servo): + """Approach a handle point g along ax (across the handle), close, report success.""" + pre = g - ax * 0.15 + yield from self.grip(side, 0.0, 10) + yield from self.reach(side, pre + np.array([0, 0, 0.08]), ax, sa, tool=0.17, n=60) + yield from self.move_hand(side, pre, ax, sa, n=30, tool=0.17) + yield from self.wait(40) + if servo: + yield from self.wrist_center(side, ax, sa, self.dark_mask, u0=self.PRE_U0) + yield from self.approach_servo(side, self.dark_mask, 0.24) + else: + yield from self.approach_until_contact(side, ax, 0.24) + self.dbg('contact%d' % side) + p = self.hand_T(side, 0.17)[:3, 3] + self.tgt[side] = dict(p=p - ax * 0.005, ax=ax, sa=sa, tool=0.17) + yield from self.wait(5) + yield from self.grip(side, 1.0, 25) + yield from self.wait(30) + yield from self.center_fingers(side, ax, sa) + self.dbg('closed%d' % side) + near = np.linalg.norm(self.hand_T(side, 0.17)[:3, 3] - self.tgt[side]['p']) < 0.05 + self._grasped = bool(self.holding(side) and near) + if not self._grasped: + yield from self.grip(side, 0.0, 10) + yield from self.move_hand(side, self.tgt[side]['p'] - ax * 0.15, ax, sa, n=30, tool=0.17) + + def fingers(self, side): + return np.array(self.ld[10:12] if side > 0 else self.ld[19:21], float) + + def center_fingers(self, side, ax, sa): + """If only one finger touches the object, re-grasp shifted along the finger line.""" + sign = self.FINGER_SIGN.get(side, 1.0) + hist = [] + for _ in range(4): + f = self.fingers(side) + asym = float(f[0] - f[1]) + hist.append(round(asym, 4)) + if f.max() < -0.0185 or abs(asym) < 0.005: + break + if len(hist) >= 2 and abs(hist[-1]) > abs(hist[-2]): + sign = -sign + shift = float(np.clip(abs(asym) * 0.6, 0.004, 0.015)) * np.sign(asym) * sign + yield from self.grip(side, 0.0, 12) + yield from self.wait(8) + p = self.tgt[side]['p'] + sa * shift + yield from self.move_hand(side, p, ax, sa, n=15, tool=0.17) + yield from self.wait(10) + yield from self.grip(side, 1.0, 20) + yield from self.wait(25) + self.FINGER_SIGN[side] = sign + self.info.setdefault('asym', []).append((side, hist)) + + def move_hands(self, targets, n): + """Move several hand targets (side -> new world position) together, keeping orientations.""" + start = {s: self.tgt[s]['p'].copy() for s in targets} + for k in range(1, n + 1): + t = k / n + t = t * t * (3 - 2 * t) + for s, p in targets.items(): + self.tgt[s] = dict(self.tgt[s], p=start[s] + t * (np.asarray(p) - start[s])) + yield + + GRASP_REL = (-0.36, 0.08, -0.1) # grasp stance relative to the perceived sandwich + RIM_R = 0.105 # pan rim radius + RIM_Z = 0.97 + RIM_AX = np.array([0.4, 0, -1.0]) + + def pan_grasp(self): + """Left hand grasps across the pan handle (finger line vertical).""" + h = self.info.get('handle') + if h is None: + return + d = _unit([h['dir'][0], h['dir'][1], 0.0]) # towards the handle end + ax = _unit(np.cross(d, [0, 0, 1.0])) + sa = np.array([0, 0, -1.0]) + end = np.asarray(h['end']) + gL = np.array([end[0], end[1], self.PAN_Z]) - d * self.PAN_FROM_END + okL = False + for attempt in range(3): + yield from self.grasp_across(1, gL, ax, sa, servo=True) + if self._grasped: + okL = True + break + gL = gL - d * 0.015 + self.info['pan_ok'] = okL + if okL: + self.info['pan_grip'] = self.tgt[1]['p'].copy() + yield from self.move_hand(1, self.tgt[1]['p'] + np.array([0, 0, self.LIFT]), ax, sa, n=60, tool=0.17) + yield from self.wait(20) + self.dbg('pan_lifted') + self.info['pan_ok'] = self.holding(1) + + SW_IN = 0.035 # grasp point: this far in from the chosen corner along the diagonal + SW_AX = np.array([0.45, 0.0, -1.0]) + SW_PITCH = 0.45 + + def sandwich_grasp(self): + """Left hand pinches a corner of the sandwich from above and lifts it out of the pan.""" + self.a[4] = -0.2 + yield from self.wait(30) + rs = [] + for _ in range(4): + r = sandwich_rect(self.tools.image('head'), self.ld.copy()) + if r is not None: + rs.append(r) + yield from self.wait(3) + self.a[4] = self.SW_PITCH + yield from self.wait(40) + self.dbg('sw_seen') + if not rs: + return + r = rs[-1] + c = r['center'] + box = r['box'] + k = int(np.argmax(box[:, 1] + 0.3 * box[:, 0])) # left-most (+y) corner, slight preference for far + corner = box[k] + diag = _unit(np.append(c - corner, 0.0)) + g = np.append(corner, self.SW_Z) + diag * self.SW_IN + sa = _unit(np.cross(diag, [0, 0, 1.0])) + ax = _unit(self.SW_AX) + self.info['sw_rect'] = (np.round(c, 3), np.round(r['size'], 3), round(float(r['ang']), 1), np.round(corner, 3)) + ok = False + for attempt in range(2): + yield from self.grip(1, 0.0, 10) + if attempt == 0: + up = self.world_T() @ np.array([0.22, 0.22, 0.42, 1.0]) + yield from self.reach(1, up[:3], ax, sa, tool=0.17, n=60) + yield from self.wait(10) + yield from self.reach(1, g + np.array([0, 0, 0.06]), ax, sa, tool=0.17, n=60) + yield from self.wait(25) + self.info.setdefault('sw_reach', []).append(round(self.info['reach_err'], 3)) + self.dbg('sw_above') + yield from self.approach_until_contact(1, np.array([0, 0, -1.0]), 0.16) + p = self.hand_T(1, 0.17)[:3, 3] + self.tgt[1] = dict(p=p + np.array([0, 0, 0.008]), ax=ax, sa=sa, tool=0.17) + yield from self.wait(5) + yield from self.grip(1, 1.0, 25) + yield from self.wait(30) + self.dbg('sw_closed') + if self.holding(1): + ok = True + break + yield from self.grip(1, 0.0, 10) + yield from self.move_hand(1, self.tgt[1]['p'] + np.array([0, 0, 0.08]), ax, sa, n=30, tool=0.17) + g = g + diag * 0.015 + self.info['sw_ok'] = ok + if ok: + yield from self.move_hand(1, self.tgt[1]['p'] + np.array([0, 0, 0.08]), ax, sa, n=80, tool=0.17) + yield from self.wait(20) + self.a[4] = 0.15 + yield from self.wait(40) + self.dbg('sw_lifted') + self.info['sw_ok'] = self.holding(1) + self.info['sw_grip'] = self.tgt[1]['p'].copy() + self.info['sw_off'] = c - self.tgt[1]['p'][:2] + + SW_Z = 0.95 + PLACE_Z = 1.00 # hand height when releasing above the board + + def carry_sandwich(self): + grip = self.tgt[1]['p'].copy() + board = self.info['board'] + delta = board - (grip[:2] + self.info.get('sw_off', np.zeros(2))) + p = self.pose() + byaw = self.base_goal[2] if self.base_goal else p[3] + self.to_rel(1) + self.to_rel(-1) + yield from self.walk_to(p[0] - 0.12, p[1], byaw, vmax=0.15) # step back from the stove first + yield from self.walk_to(p[0] + delta[0] - 0.12, p[1] + delta[1], byaw, vmax=0.15) + yield from self.walk_to(p[0] + delta[0], p[1] + delta[1], byaw, vmax=0.10) + yield from self.wait(30) + self.to_world(1) + self.to_world(-1) + self.dbg('at_board') + t = self.tgt[1] + yield from self.move_hand(1, np.array([t['p'][0], t['p'][1], self.PLACE_Z]), t['ax'], t['sa'], n=60, tool=0.17) + yield from self.wait(20) + yield from self.grip(1, 0.0, 20) + yield from self.wait(20) + yield from self.move_hand(1, self.tgt[1]['p'] + np.array([0, 0, 0.10]), t['ax'], t['sa'], n=40, tool=0.17) + self.dbg('placed') + + def to_rel(self, side): + """Freeze a hand target in the pelvis frame (it then moves with the body).""" + t = self.tgt[side] + if t is None or t.get('rel'): + return + self.tgt[side] = dict(p=self.to_pelvis(t['p']), ax=self.vec_to_pelvis(t['ax']), + sa=self.vec_to_pelvis(t['sa']), tool=t.get('tool', 0.17), rel=True) + + def to_world(self, side): + t = self.tgt[side] + if t is None or not t.get('rel'): + return + R = self.world_T() + self.tgt[side] = dict(p=(R @ np.append(t['p'], 1.0))[:3], ax=R[:3, :3] @ t['ax'], + sa=R[:3, :3] @ t['sa'], tool=t.get('tool', 0.17)) + + POUR_LEAD = 0.07 # sandwich placed this far behind (+x) the board centre before pouring + CARRY_Z = 1.02 # grip height while carrying + + BOARD_HALF_W = 0.17 # half width (along y) of the chopping board + PAN_FOOT = 0.10 # pan centre to far bottom edge + EDGE_Z = 0.935 # height of the pivot (board edge / counter) + + def carry(self): + """Drag the pan (far rim on the counter) sideways until it reaches the board.""" + h = self.info['handle'] + d = _unit([h['dir'][0], h['dir'][1]]) + sw = self.info.get('sandwich') + grip = self.tgt[1]['p'].copy() + c = sw['center'][:2] if sw is not None else grip[:2] - d * 0.22 + board = self.info['board'] + y_edge = board[1] + self.BOARD_HALF_W + far = c[1] - self.PAN_FOOT # far bottom edge of the pan (y) + dy = (y_edge + 0.005) - far + p = self.pose() + byaw = self.base_goal[2] if self.base_goal else p[3] + self.info['board_stance'] = (p[0], p[1] + dy, byaw) + self.info['pivot'] = np.array([grip[0], y_edge, self.EDGE_Z]) + self.to_rel(1) + yield from self.walk_to(p[0], p[1] + dy, byaw, vmax=0.12) + yield from self.wait(30) + self.to_world(1) + self.dbg('at_board') + + POUR_DEG = 55.0 + + def pour(self): + """Raise the handle: rotate the hand about the pan's far bottom edge.""" + t = self.tgt[1] + p0, ax0, sa0 = t['p'].copy(), t['ax'].copy(), t['sa'].copy() + piv = self.info['pivot'].copy() + piv[0] = p0[0] + h = self.info['handle'] + k = _unit(np.cross([0, 0, 1.0], [h['dir'][0], h['dir'][1], 0.0])) # handle side rises + k = -k + for deg in np.linspace(0, self.POUR_DEG, 120): + R = _rodrigues(k, np.radians(deg)) + self.tgt[1] = dict(p=piv + R @ (p0 - piv), ax=R @ ax0, sa=R @ sa0, tool=0.17) + yield + yield from self.wait(60) + self.dbg('poured') + for deg in np.linspace(self.POUR_DEG, 20, 60): + R = _rodrigues(k, np.radians(deg)) + self.tgt[1] = dict(p=piv + R @ (p0 - piv), ax=R @ ax0, sa=R @ sa0, tool=0.17) + yield + self.dbg('unpoured') + + def act(self, obs, tools): + self.obs = obs + next(self.gen) + self.apply_base() + self.apply_targets() + lo = np.array(tools.info['raw_low']) if hasattr(tools, 'info') else None + a = self.a.copy() + if lo is not None: + a = np.clip(a, lo, np.array(tools.info['raw_high'])) + return a.astype(np.float32) diff --git a/policies/sandwich_remove/opus-s2/episodes.csv b/policies/sandwich_remove/opus-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..df9925e0105b09d840cacf2af153f56eaf497ada --- /dev/null +++ b/policies/sandwich_remove/opus-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,3150,timeout,0 +620003,0,3150,timeout,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,3150,timeout,0 +620009,0,3150,timeout,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,0,3150,timeout,0 +620014,0,3150,timeout,0 +620015,0,3150,timeout,0 +620016,0,3150,timeout,0 +620017,0,3150,timeout,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,3150,timeout,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,3150,timeout,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,3150,timeout,0 +620031,0,1431,terminated,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,3150,timeout,0 +620043,0,1284,fell,1 +620044,0,3150,timeout,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,0,1348,terminated,0 +620048,0,3150,timeout,0 +620049,0,3150,timeout,0 +620050,0,3150,timeout,0 +620051,0,3150,timeout,0 +620052,0,3150,timeout,0 +620053,0,3150,timeout,0 +620054,0,3150,timeout,0 +620055,0,3150,timeout,0 +620056,0,1006,terminated,0 +620057,0,3150,timeout,0 +620058,0,3150,timeout,0 +620059,0,3150,timeout,0 +620060,0,3150,timeout,0 +620061,0,3150,timeout,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,0,3150,timeout,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,3150,timeout,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,3150,timeout,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,3150,timeout,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,0,3150,timeout,0 +620084,0,3150,timeout,0 +620085,0,3150,timeout,0 +620086,0,3150,timeout,0 +620087,0,3150,timeout,0 +620088,0,3150,timeout,0 +620089,0,3150,timeout,0 +620090,0,3150,timeout,0 +620091,0,3150,timeout,0 +620092,0,3150,timeout,0 +620093,0,3150,timeout,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,0,3150,timeout,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/opus-s2/g1kin.py b/policies/sandwich_remove/opus-s2/g1kin.py new file mode 100644 index 0000000000000000000000000000000000000000..f44b9770e8b4ae19a60c4926d04b2b85c1986409 --- /dev/null +++ b/policies/sandwich_remove/opus-s2/g1kin.py @@ -0,0 +1,137 @@ +"""Forward / inverse kinematics of the G1 arms (pelvis frame), from the G1 URDF geometry.""" +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, p): + M = np.eye(4) + M[:3, :3] = R + M[:3, 3] = p + return M + + +def _chain(side): + s = 1 if side == 'L' else -1 + return [ + (_T(rpy(s * 0.27931, 5.4949e-05, -s * 0.00019159), [0.0039563, s * 0.10022, 0.23778]), 'y'), + (_T(rpy(-s * 0.27925, 0, 0), [0, s * 0.038, -0.013831]), 'x'), + (_T(np.eye(3), [0, s * 0.00624, -0.1032]), 'z'), + (_T(np.eye(3), [0.015783, 0, -0.080518]), 'y'), + (_T(np.eye(3), [0.100, s * 0.00188791, -0.010]), 'x'), + (_T(np.eye(3), [0.038, 0, 0]), 'y'), + (_T(np.eye(3), [0.046, 0, 0]), 'z'), + ] + + +CHAINS = {'L': _chain('L'), 'R': _chain('R')} +AX = {'x': rx, 'y': ry, 'z': rz} + +# shoulder roll is limited further than the joint range: rolling inward makes the +# upper arm hit the torso (measured: the left arm stalls near -0.05..-0.15) +LOW = {'L': np.array([-3.0892, -0.02, -2.618, -1.0472, -1.97222, -1.61443, -1.61443]), + 'R': np.array([-3.0892, -1.5882, -2.618, -1.0472, -1.97222, -1.61443, -1.61443])} +HIGH = {'L': np.array([2.6704, 2.2515, 2.618, 2.0944, 1.97222, 1.61443, 1.61443]), + 'R': np.array([2.6704, 0.02, 2.618, 2.0944, 1.97222, 1.61443, 1.61443])} + +TOOL = 0.13 # wrist-yaw joint to the grasp point between the fingers, m + + +def torso_T(waist): + y, r, p = waist + return _T(rz(y), [0, 0, 0]) @ _T(rx(r), [-0.0039635, 0, 0.044]) @ _T(ry(p), [0, 0, 0]) + + +def fk(side, q, waist=(0.0, 0.0, 0.0), tool=TOOL): + """4x4 pose of the tool frame (x along the fingers) in the pelvis frame.""" + M = torso_T(waist) + for (J, ax), a in zip(CHAINS[side], q): + M = M @ J @ _T(AX[ax](a), [0, 0, 0]) + return M @ _T(np.eye(3), [tool, 0, 0]) + + +def _rot_err(Rc, Rd): + E = Rd @ Rc.T + return 0.5 * np.array([E[2, 1] - E[1, 2], E[0, 2] - E[2, 0], E[1, 0] - E[0, 1]]) + + +def ik(side, pos, R=None, q0=None, waist=(0.0, 0.0, 0.0), tool=TOOL, wrot=0.3, + axis_only=None, rest=None, wrest=0.01, fixed=None, axis_y=None): + """Bounded least-squares IK for the tool point. + + pos: target tool position (pelvis frame). R: target rotation, or + axis_only: target direction of the tool x-axis (fingers). rest: posture + the solution is pulled toward (weight wrest). fixed: dict joint->value. + Returns (q, pos_err, rot_err). + """ + from scipy.optimize import least_squares + lo, hi = LOW[side] + 0.01, HIGH[side] - 0.01 + q0 = np.zeros(7) if q0 is None else np.array(q0, dtype=float) + q0 = np.clip(q0, lo, hi) + rest = q0.copy() if rest is None else np.asarray(rest, float) + pos = np.asarray(pos, float) + free = [j for j in range(7) if not fixed or j not in fixed] + + def full(x): + q = q0.copy() + if fixed: + for j, v in fixed.items(): + q[j] = v + q[free] = x + return q + + def res(x): + q = full(x) + M = fk(side, q, waist, tool) + e = [pos - M[:3, 3]] + if R is not None: + e.append(wrot * 0.5 * (M[:3, :3] - R).ravel()) + elif axis_only is not None: + e.append(wrot * (np.asarray(axis_only) - M[:3, 0])) + elif axis_y is not None: + e.append(wrot * (np.asarray(axis_y) - M[:3, 1])) + e.append(wrest * (q - rest)) + return np.concatenate(e) + + sol = least_squares(res, q0[free], bounds=(lo[free], hi[free]), xtol=1e-8, ftol=1e-10, max_nfev=200) + q = full(sol.x) + e = res(sol.x) + return q, float(np.linalg.norm(e[:3])), float(np.linalg.norm(e[3:-7])) / wrot if len(e) > 10 else 0.0 + + +_SEEDS_L = [np.array(s, float) for s in ( + [-0.5, 0.3, 0, 0.5, 0, 0, 0], [-1.0, 0.3, 0, 1.0, 0, 0, 0], [-1.5, 0.3, 0.5, 1.2, 0, 0, 0], + [-0.5, 0.0, -0.5, 1.5, 0, 0, 0], [0, 0.2, 0, 0, 0, 0, 0], [-1.0, 0.8, -0.5, 0.5, 0.5, 0.5, 0], + [-1.2, 0.2, 0.8, 1.4, -1.0, 0, 0], [-0.8, 0.1, -0.8, 1.6, 1.0, 0, 0])] +SEEDS = {'L': _SEEDS_L, 'R': [s * np.array([1, -1, -1, 1, -1, 1, -1]) for s in _SEEDS_L]} + + +def ik_best(side, pos, q0=None, tol=2e-3, **kw): + """IK from several starting postures (q0 first); returns the best (q, pos_err, rot_err).""" + starts = ([np.asarray(q0, float)] if q0 is not None else []) + SEEDS[side] + best = None + for k, s in enumerate(starts): + q, ep, er = ik(side, pos, q0=s, **kw) + score = ep + 0.1 * er + (0.002 * np.linalg.norm(q - starts[0]) if q0 is not None else 0.0) + if best is None or score < best[3]: + best = (q, ep, er, score) + if k == 0 and q0 is not None and ep < tol and er < 0.02: + break + return best[0], best[1], best[2] diff --git a/policies/sandwich_remove/opus-s2/policy.py b/policies/sandwich_remove/opus-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..87aab5253d7069512c6319d3de99afc3d4289952 --- /dev/null +++ b/policies/sandwich_remove/opus-s2/policy.py @@ -0,0 +1,439 @@ +"""Sandwich removal policy for the G1 (hand-written state machine). + +Pipeline + 1. walk to a viewing pose in front of the hob, find the pan handle in the head + image (dark bar left of the pan) and estimate its end point and direction; + 2. walk to a grasp pose, squat, grasp the handle with the left hand + (vertical pinch), stand up (lifts the pan a few cm); + 3. side-step to the right carrying the pan next to the chopping board, set it down; + 4. lean back, locate the sandwich (yellow blob) in the head image, correct the + base position sideways so the pan's far rim sits at the board edge; + 5. lean forward and rotate the grip about the pan's far rim (closed-loop IK + in the world frame) so the pan tilts and the sandwich slides onto the board. + +Kinematics come from g1kin.py (G1 arm geometry); the head camera model was +calibrated offline from the robot's own camera views. +""" + +import cv2 +import numpy as np +from scipy.spatial.transform import Rotation as Rot + +import g1kin + +# ---------------------------------------------------------------- constants +TUCK_L = np.array([-0.2, 0.15, 0, 1.5, 0, 0, 0]) +TUCK_R = np.array([-0.2, -0.15, 0, 1.5, 0, 0, 0]) +RL = np.array([-1.0, 0.2, 0, 0.8, 0, 0, 0]) + +OBS_POSE = (0.30, 0.40, 0.0) # viewing pose in front of the pan +GOFF = 0.13 # grasp point: distance from handle end along the handle +CDIST = 0.16 # grasp point -> pan centre +GZ = 0.877 # handle height (world) +GP = np.array([0.42, 0.28]) # grasp point relative to the pelvis when grasping +SQ = 0.67 # squat height for the grasp +PT = np.array([0.42, 0.18, 0.19]) # carry position of the grip (pelvis frame) +CDES = np.array([0.66, -0.30]) # pan centre target after the carry (world) +ZLOW = 0.147 # grip height with the pan resting on the counter (pelvis frame) +VIEWP = -0.2 # torso pitch for looking at the pan +SZ = 0.885 # sandwich top height (world) +SY = -0.30 # sandwich y target before tilting (board edge at y = -0.42) +RPAN = 0.06 # sandwich -> pivot (far rim) distance +PIVZ = 0.03 # pivot below the grip +ARC = 62.0 # tilt angle, deg +TILTP = 0.6 # torso pitch while tilting (reach) +SHAKE = 8.0 # deg, oscillation at the top of the tilt + +# head camera (fixed to the torso), calibrated at waist pitch 0.06 +_CAM_RV = np.array([-1.997705, 1.993675, -0.415088]) +CAM_R = Rot.from_rotvec(_CAM_RV).as_matrix() # columns: image right, image down, view dir (pelvis frame) +CAM_F = 56.597115 +CAM_P = np.array([0.185833, -0.000255, 0.33]) +_T_FIT_INV = np.linalg.inv(g1kin.torso_T((0, 0, 0.06))) + + +# ---------------------------------------------------------------- helpers +def wrap(a): + return (a + np.pi) % (2 * np.pi) - np.pi + + +def pel_T(pose): + x, y, z, yaw = pose + c, s = np.cos(yaw), np.sin(yaw) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]), np.array([x, y, z]) + + +def world_to_pel(Pw, pose): + R, t = pel_T(pose) + return R.T @ (np.asarray(Pw) - t) + + +def pel_to_world(p, pose): + R, t = pel_T(pose) + return R @ p + t + + +def rot_to_pel(v, yaw): + c, s = np.cos(yaw), np.sin(yaw) + return np.array([c * v[0] + s * v[1], -s * v[0] + c * v[1], v[2]]) + + +def Rxy(x, y): + x = np.asarray(x, float) + x = x / np.linalg.norm(x) + y = np.asarray(y, float) + y = y - x * (x @ y) + y = y / np.linalg.norm(y) + return np.stack([x, y, np.cross(x, y)], 1) + + +def walk_cmd(lo, xt, yt, yawt=0.0, tol=0.02, vmax=0.25): + x, y, yaw = lo[21], lo[22], lo[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 + vx = np.clip(1.5 * bx, -vmax, vmax) + vy = np.clip(1.5 * by, -0.2, 0.2) + eyaw = wrap(yawt - yaw) + wz = np.clip(2.0 * eyaw, -0.5, 0.5) + done = np.hypot(bx, by) < tol + if done: + vx = vy = 0.0 + elif np.hypot(vx, vy) < 0.06: + k = 0.06 / max(np.hypot(vx, vy), 1e-6) + vx, vy = vx * k, vy * k + if abs(eyaw) < 0.03: + wz = 0.0 + return vx, vy, wz, done and abs(eyaw) < 0.05 + + +class ArmCtl: + """Joint target tracking with a small integral term against gravity sag.""" + + def __init__(self, side, ki=0.03, imax=0.25): + self.sl = slice(3, 10) if side == 'L' else slice(12, 19) + self.I = np.zeros(7) + self.ki = ki + self.imax = imax + + def cmd(self, q_des, lo, active=True): + if active: + self.I = np.clip(self.I + self.ki * (q_des - lo[self.sl]), -self.imax, self.imax) + return q_des + self.I + + +def interp_path(qs, a): + m = len(qs) - 1 + s = min(max(a, 0.0), 1.0) * m + i = min(int(s), m - 1) + f = s - i + return (1 - f) * qs[i] + f * qs[i + 1] + + +def cart_path(side, q0, p0, R0, p1, R1, waist, m=8): + qs = [np.asarray(q0, float)] + q = qs[0] + r = Rot.from_matrix(R0.T @ R1).as_rotvec() + for k in range(1, m + 1): + a = k / m + p = (1 - a) * np.asarray(p0) + a * np.asarray(p1) + R = R0 @ Rot.from_rotvec(a * r).as_matrix() + q, e1, e2 = g1kin.ik(side, p, R=R, q0=q, wrot=1.0, rest=RL, wrest=0.005, waist=waist) + qs.append(q) + return qs + + +def ik_fixed_wrist(p, R, q0, waist): + fix = {5: 0.0, 6: 0.0} + starts = ([q0] if q0 is not None else []) + g1kin.SEEDS['L'] + best = None + for s in starts: + q, e1, e2 = g1kin.ik('L', p, R=R, q0=s, wrot=1.0, fixed=fix, waist=waist, rest=RL, wrest=0.005) + sc = e1 + 0.05 * e2 + if best is None or sc < best[3]: + best = (q, e1, e2, sc) + if q0 is not None and s is q0 and e1 < 0.003: + break + return best[:3] + + +def cam_ray(uv, pose, waist=None): + """camera centre and ray (world) through pixel uv (84x84 head image).""" + if waist is None: + RC, CP = CAM_R, CAM_P + else: + D = g1kin.torso_T(waist) @ _T_FIT_INV + RC = D[:3, :3] @ CAM_R + CP = D[:3, :3] @ CAM_P + D[:3, 3] + Rp, tp = pel_T(pose) + d = np.array([(uv[0] - 41.5) / CAM_F, (uv[1] - 41.5) / CAM_F, 1.0]) + return Rp @ CP + tp, Rp @ RC @ d + + +def pixel_to_plane(uv, pose, z, waist=None): + c, d = cam_ray(uv, pose, waist) + return c + (z - c[2]) / d[2] * d + + +def detect_handle(im, pose): + """end point (world) and unit direction (end -> pan) of the pan handle.""" + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + m = (hsv[..., 2] < 60) & (hsv[..., 1] < 110) + m[45:] = False + n, lab, st, _ = cv2.connectedComponentsWithStats(m.astype(np.uint8)) + cands = [k for k in range(1, n) if 15 < st[k, cv2.CC_STAT_AREA] < 600] + if not cands: + return None + k = min(cands, key=lambda k: st[k, cv2.CC_STAT_LEFT]) + ys, xs = np.where(lab == k) + if xs.min() == 0: + return None + pts = [] + for x in range(xs.min(), xs.max() + 1): + r = ys[xs == x] + if len(r): + pts.append((x, r.mean(), r.max() - r.min())) + pts = np.array(pts, float) + bar = pts[(pts[:, 0] >= xs.min() + 9) & (pts[:, 2] < 5)] + if len(bar) < 5: + return None + end = pixel_to_plane(np.array([xs.min() - 0.5, pts[0, 1]]), pose, 0.880) + wb = np.array([pixel_to_plane(p[:2], pose, 0.877) for p in bar]) + u = wb[-1] - wb[0] + u[2] = 0 + nu = np.linalg.norm(u) + if nu < 1e-6: + return None + u /= nu + if u[1] > 0.3: # the handle points from its end toward -y (pan side) + return None + return end, u + + +def detect_sandwich(im, pose, waist, near, rad=0.17): + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV) + m = (hsv[..., 0] >= 25) & (hsv[..., 0] <= 36) & (hsv[..., 1] > 75) & (hsv[..., 2] > 180) + vs, us = np.where(m) + pts = [] + for u, v in zip(us, vs): + p = pixel_to_plane((u + 0.5, v + 0.5), pose, SZ, waist) + if np.hypot(p[0] - near[0], p[1] - near[1]) < rad: + pts.append(p) + if len(pts) < 10: + return None + return np.median(np.array(pts), axis=0) + + +# ---------------------------------------------------------------- policy +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.float32) + self.state = 'walk_obs' + self.t_state = 0 + self.armL = ArmCtl('L') + self.qL = TUCK_L.copy() + self.qR = TUCK_R.copy() + self.grip = 0.6 + self.height = 0.74 + self.pitch = 0.0 + self.k = 0 + self.target = OBS_POSE + self.segs = [] + self.ncorr = 0 + + def goto(self, s, t): + self.state = s + self.t_state = t + + def run_segs(self, dt, t, nxt): + qs, n, g = self.segs[self.k] + a = min(1.0, (dt + 1) / n) + self.qL = interp_path(qs, a) + if g is not None: + self.grip = g + if dt + 1 >= n: + if self.k < len(self.segs) - 1: + self.k += 1 + self.t_state = t + 1 + else: + self.k = 0 + self.goto(nxt, t) + + def record_grip(self, lo): + pose = lo[21:25] + M = g1kin.fk('L', self.qL, waist=lo[0:3]) + Rp, _ = pel_T(pose) + self.Wg = pel_to_world(M[:3, 3], pose) + self.Wr = Rp @ M[:3, :3] + + def hold_left_world(self, lo, Gw=None, Rw=None): + pose = lo[21:25] + Rp, tp = pel_T(pose) + Gw = self.Wg if Gw is None else Gw + Rw = self.Wr if Rw is None else Rw + self.qL, _, _ = g1kin.ik('L', Rp.T @ (Gw - tp), R=Rp.T @ Rw, q0=self.qL, wrot=1.0, rest=RL, + wrest=0.003, waist=lo[0:3]) + + def act(self, obs, tools): + t = int(obs['t']) + lo = np.asarray(obs['low_dim_obs'], dtype=float) + raw = self.hold.copy() + b = min(1.0, t / 30) + if t < 30: + self.qR = b * TUCK_R + (1 - b) * self.hold[12:19] + dt = t - self.t_state + st = self.state + + if st in ('walk_obs', 'walk_grasp'): + if st == 'walk_obs': + self.qL = b * TUCK_L + (1 - b) * self.hold[5:12] + if t >= 10: + vx, vy, wz, done = walk_cmd(lo, *self.target, tol=0.02) + raw[0], raw[1], raw[3] = vx, vy, wz + if done or dt > 300: + self.goto('settle_' + st[5:], t) + + elif st == 'settle_obs': + if dt > 25: + pose = lo[21:25].copy() + r = detect_handle(tools.image('head'), pose) + if r is None: + end, u = np.array([0.709, 0.479, 0.880]), np.array([0.0, -1.0, 0.0]) + else: + end, u = r + self.G = end + GOFF * u + self.G[2] = GZ + self.u = u + self.hx = np.array([-u[1], u[0], 0.0]) + if self.hx[0] < 0: + self.hx = -self.hx + self.C = self.G + CDIST * u + self.target = (self.G[0] - GP[0], self.G[1] - GP[1], 0.0) + self.goto('walk_grasp', t) + + elif st == 'settle_grasp': + self.height = max(SQ, self.height - 0.003) + if dt > 60: + pose = lo[21:25].copy() + waist = lo[0:3].copy() + d = rot_to_pel(self.hx, pose[3]) + R = Rxy(d, (0, 0, 1)) + Gp = world_to_pel(self.G, pose) + P1 = Gp - 0.10 * d + P0 = P1 + np.array([0, 0, 0.05]) + q0, _, _ = ik_fixed_wrist(P0, R, None, waist) + q1, _, _ = ik_fixed_wrist(P1, R, q0, waist) + q2, _, _ = ik_fixed_wrist(Gp, R, q1, waist) + self.segs = [([TUCK_L, q0], 70, 0.0), ([q0, q1], 40, 0.0), ([q1, q2], 80, 0.0), + ([q2, q2], 20, 0.5), ([q2, q2], 20, 1.0)] + self.k = 0 + self.goto('grasp', t) + + elif st == 'grasp': + self.run_segs(dt, t, 'stand') + + elif st == 'stand': + self.height = min(0.74, self.height + 0.002) + if dt > 60: + waist = lo[0:3].copy() + M = g1kin.fk('L', self.qL, waist=waist) + Hp, R0 = M[:3, 3], M[:3, :3] + self.R0 = R0 + self.segs = [(cart_path('L', self.qL, Hp, R0, PT, R0, waist, m=10), 80, 1.0)] + self.k = 0 + self.Cp = world_to_pel(self.C, lo[21:25]) + (PT - Hp) + self.goto('repos', t) + + elif st == 'repos': + self.run_segs(dt, t, 'carry') + + elif st == 'carry': + yaw = lo[24] + c, s = np.cos(yaw), np.sin(yaw) + off = np.array([c * self.Cp[0] - s * self.Cp[1], s * self.Cp[0] + c * self.Cp[1]]) + tgt = (CDES[0] - off[0], CDES[1] - off[1], 0.0) + vx, vy, wz, done = walk_cmd(lo, *tgt, tol=0.03, vmax=0.15) + wz = np.clip(3.0 * (0.0 - yaw), -0.8, 0.8) if abs(yaw) > 0.03 else 0.0 + done = done and abs(yaw) < 0.08 + raw[0], raw[1], raw[3] = vx, np.clip(vy, -0.15, 0.15), wz + if done or dt > 450: + self.goto('settle_lower', t) + + elif st == 'settle_lower': + if dt > 25: + waist = lo[0:3].copy() + Hp = g1kin.fk('L', self.qL, waist=waist)[:3, 3] + Hl = np.array([Hp[0], Hp[1], ZLOW]) + self.segs = [(cart_path('L', self.qL, Hp, self.R0, Hl, self.R0, waist, m=6), 60, 1.0)] + self.k = 0 + self.goto('lower', t) + + elif st == 'lower': + self.run_segs(dt, t, 'lean_view') + if self.state == 'lean_view': + self.record_grip(lo) + + elif st == 'lean_view': + self.pitch = max(VIEWP, self.pitch - 0.005) + self.hold_left_world(lo) + if dt > 70: + pose = lo[21:25].copy() + Cw = self.Wg + CDIST * self.u + S = detect_sandwich(tools.image('head'), pose, lo[0:3], Cw) + self.S = Cw if S is None else S + dy = SY - self.S[1] + if abs(dy) > 0.03 and self.ncorr < 2: + self.ncorr += 1 + p = lo[21:25] + self.ctgt = (p[0], p[1] + dy, p[3]) + self.goto('correct', t) + else: + self.goto('settle_tilt', t) + + elif st == 'correct': + vx, vy, wz, done = walk_cmd(lo, *self.ctgt, tol=0.015, vmax=0.12) + raw[0], raw[1], raw[3] = vx, np.clip(vy, -0.12, 0.12), wz + if done or dt > 250: + self.goto('recorrect', t) + + elif st == 'recorrect': + if dt > 30: + self.record_grip(lo) + self.goto('lean_view', t - 71) + + elif st == 'settle_tilt': + self.hold_left_world(lo) + self.pitch = min(TILTP, self.pitch + 0.005) + if dt > 150: + w = self.S - self.Wg + w[2] = 0 + dist = np.linalg.norm(w) + w = w / max(dist, 1e-6) + P = self.Wg + (dist + RPAN) * w + P[2] = self.Wg[2] - PIVZ + axis = np.cross([0, 0, 1.0], w) + self.arc = (P, axis / np.linalg.norm(axis), self.Wg.copy(), self.Wr.copy()) + self.goto('tilt', t) + + elif st == 'tilt': + P, axis, G0, R0w = self.arc + ang = ARC * min(1.0, (dt + 1) / 200) + if 220 < dt < 340: + ang += SHAKE * np.sin((dt - 220) * 2 * np.pi / 30) + Rm = Rot.from_rotvec(axis * np.radians(ang)).as_matrix() + Gw = P + Rm @ (G0 - P) + if dt > 380: + sep = min(1.0, (dt - 380) / 60) + Gw = Gw + sep * np.array([0, 0, 0.05]) - sep * 0.04 * np.cross(axis, [0, 0, 1.0]) + self.hold_left_world(lo, Gw, Rm @ R0w) + + raw[2] = self.height + raw[4] = self.pitch + raw[5:12] = self.armL.cmd(self.qL, lo, active=st not in ('walk_obs', 'settle_obs', 'walk_grasp', + 'settle_grasp')) + raw[12:19] = self.qR + raw[19] = self.grip + raw[20] = 0.6 + return raw diff --git a/policies/sandwich_remove/opus-s3/camera.py b/policies/sandwich_remove/opus-s3/camera.py new file mode 100644 index 0000000000000000000000000000000000000000..d725714d31c370b1273839da1fd6e3cde96303b4 --- /dev/null +++ b/policies/sandwich_remove/opus-s3/camera.py @@ -0,0 +1,72 @@ +"""Head-camera model (calibrated against the arm forward kinematics) and frame helpers.""" +import numpy as np + +from g1kin import _rx, _ry, _rz + +# camera position in torso frame, pitch about torso y, focal length (px, 84x84 image) +CAM_POS = np.array([0.0466, 0.0, 0.4275]) +CAM_PITCH = 1.0069 +CAM_F = 80.26 +C0 = 41.5 # principal point +PELVIS_PITCH = 0.08 # forward lean of the pelvis while standing (from floor consistency) + +WAIST_ROLL_OFF = np.array([-0.0039635, 0.0, 0.035]) +WAIST_PITCH_OFF = np.array([0.0, 0.0, 0.019]) + + +def torso_pose(lo, pelvis_pitch=PELVIS_PITCH): + """World pose (p, R) of the torso link from low_dim_obs.""" + x, y, z, yaw = lo[21:25] + wy, wr, wp = lo[0:3] + R = _rz(yaw) @ _ry(pelvis_pitch) + p = np.array([x, y, z]) + R = R @ _rz(wy) + p = p + R @ WAIST_ROLL_OFF + R = R @ _rx(wr) + p = p + R @ WAIST_PITCH_OFF + R = R @ _ry(wp) + return p, R + + +def cam_pose(lo, **kw): + p, R = torso_pose(lo, **kw) + return p + R @ CAM_POS, R @ _ry(CAM_PITCH) + + +def project_torso(P): + """Torso-frame points -> pixels (u, v).""" + d = (np.atleast_2d(P) - CAM_POS) @ _ry(CAM_PITCH) + return np.stack([C0 - CAM_F * d[:, 1] / d[:, 0], C0 - CAM_F * d[:, 2] / d[:, 0]], 1) + + +def project_world(P, lo, **kw): + c, R = cam_pose(lo, **kw) + d = (np.atleast_2d(P) - c) @ R + return np.stack([C0 - CAM_F * d[:, 1] / d[:, 0], C0 - CAM_F * d[:, 2] / d[:, 0]], 1) + + +def ray_torso(u, v): + """Pixel -> (origin, unit direction) in torso frame.""" + d = np.array([1.0, (C0 - u) / CAM_F, (C0 - v) / CAM_F]) + d = _ry(CAM_PITCH) @ d + return CAM_POS.copy(), d / np.linalg.norm(d) + + +def pixel_to_plane_world(u, v, lo, zplane, **kw): + """Intersect the pixel ray with the world horizontal plane z = zplane.""" + o, d = ray_torso(u, v) + p, R = torso_pose(lo, **kw) + o = p + R @ o + d = R @ d + t = (zplane - o[2]) / d[2] + return o + t * d + + +def world_to_torso(w, lo, **kw): + p, R = torso_pose(lo, **kw) + return R.T @ (np.asarray(w) - p) + + +def torso_to_world(t, lo, **kw): + p, R = torso_pose(lo, **kw) + return p + R @ np.asarray(t) diff --git a/policies/sandwich_remove/opus-s3/episodes.csv b/policies/sandwich_remove/opus-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..06a79771dedbedf12473fce2ee2f8895c54a640c --- /dev/null +++ b/policies/sandwich_remove/opus-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,3150,timeout,0 +620001,0,3150,timeout,0 +620002,0,3150,timeout,0 +620003,1,1873,success,0 +620004,0,3150,timeout,0 +620005,0,3150,timeout,0 +620006,0,3150,timeout,0 +620007,0,3150,timeout,0 +620008,0,3150,timeout,0 +620009,0,3150,timeout,0 +620010,0,3150,timeout,0 +620011,0,3150,timeout,0 +620012,0,3150,timeout,0 +620013,0,3150,timeout,0 +620014,0,3150,timeout,0 +620015,0,3150,timeout,0 +620016,0,3150,timeout,0 +620017,0,3150,timeout,0 +620018,0,3150,timeout,0 +620019,0,3150,timeout,0 +620020,0,3150,timeout,0 +620021,0,3150,timeout,0 +620022,0,3150,timeout,0 +620023,0,3150,timeout,0 +620024,0,3150,timeout,0 +620025,0,3150,timeout,0 +620026,0,3150,timeout,0 +620027,0,3150,timeout,0 +620028,0,3150,timeout,0 +620029,0,3150,timeout,0 +620030,0,3150,timeout,0 +620031,0,3150,timeout,0 +620032,0,3150,timeout,0 +620033,0,3150,timeout,0 +620034,0,3150,timeout,0 +620035,0,3150,timeout,0 +620036,0,3150,timeout,0 +620037,0,3150,timeout,0 +620038,0,3150,timeout,0 +620039,0,3150,timeout,0 +620040,0,3150,timeout,0 +620041,0,3150,timeout,0 +620042,0,3150,timeout,0 +620043,0,3150,timeout,0 +620044,0,3150,timeout,0 +620045,0,3150,timeout,0 +620046,0,3150,timeout,0 +620047,0,3150,timeout,0 +620048,0,3150,timeout,0 +620049,0,3150,timeout,0 +620050,0,3150,timeout,0 +620051,0,3150,timeout,0 +620052,0,3150,timeout,0 +620053,0,3150,timeout,0 +620054,0,3150,timeout,0 +620055,0,3150,timeout,0 +620056,0,3150,timeout,0 +620057,0,3150,timeout,0 +620058,0,3150,timeout,0 +620059,0,3150,timeout,0 +620060,0,3150,timeout,0 +620061,0,3150,timeout,0 +620062,0,3150,timeout,0 +620063,0,3150,timeout,0 +620064,0,3150,timeout,0 +620065,0,3150,timeout,0 +620066,0,3150,timeout,0 +620067,0,3150,timeout,0 +620068,0,3150,timeout,0 +620069,0,3150,timeout,0 +620070,0,3150,timeout,0 +620071,0,3150,timeout,0 +620072,0,3150,timeout,0 +620073,0,3150,timeout,0 +620074,0,3150,timeout,0 +620075,0,3150,timeout,0 +620076,0,3150,timeout,0 +620077,0,3150,timeout,0 +620078,0,3150,timeout,0 +620079,0,3150,timeout,0 +620080,0,3150,timeout,0 +620081,0,3150,timeout,0 +620082,0,3150,timeout,0 +620083,0,3150,timeout,0 +620084,0,3150,timeout,0 +620085,0,3150,timeout,0 +620086,0,3150,timeout,0 +620087,0,3150,timeout,0 +620088,0,3150,timeout,0 +620089,0,3150,timeout,0 +620090,0,3150,timeout,0 +620091,0,3150,timeout,0 +620092,0,3150,timeout,0 +620093,0,3150,timeout,0 +620094,0,3150,timeout,0 +620095,0,3150,timeout,0 +620096,0,3150,timeout,0 +620097,0,3150,timeout,0 +620098,0,3150,timeout,0 +620099,0,3150,timeout,0 diff --git a/policies/sandwich_remove/opus-s3/g1kin.py b/policies/sandwich_remove/opus-s3/g1kin.py new file mode 100644 index 0000000000000000000000000000000000000000..9062d68bbe10822973d332fb04cb78eee2afa477 --- /dev/null +++ b/policies/sandwich_remove/opus-s3/g1kin.py @@ -0,0 +1,88 @@ +"""Forward kinematics of the G1 arms in the torso frame (from the G1 URDF geometry).""" +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 _chain(side): + s = 1.0 if side == "L" else -1.0 + return [ + # (origin xyz, origin rpy, axis) + ((0.0039563, s * 0.10022, 0.23778), (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"), + ] + + +_CH = {k: [(np.array(o), _rpy(*r), ax) for o, r, ax in _chain(k)] for k in "LR"} +_AX = {"x": _rx, "y": _ry, "z": _rz} + + +def fk(q, side="R", tip=(0.0, 0.0, 0.0)): + """Return (position, rotation) of a point fixed in the wrist-yaw link, torso frame.""" + R = np.eye(3) + p = np.zeros(3) + for (o, Ro, ax), a in zip(_CH[side], q): + p = p + R @ o + R = R @ Ro @ _AX[ax](a) + return p + R @ np.asarray(tip), R + + +def ik(target, q0, side="R", tip=(0.12, 0, 0), Rtarget=None, wrot=0.3, qmin=None, qmax=None, + axes_only=None, iters=60, qref=None, reg=0.0): + """Damped least squares IK. Rtarget: 3x3 desired rotation (or None). + axes_only: list of (local_axis, world_dir) pairs to align instead of full rotation.""" + q = np.array(q0, dtype=float) + lo = np.array(qmin if qmin is not None else [-3.0, -1.58, -2.6, -1.04, -1.97, -1.61, -1.61]) + hi = np.array(qmax if qmax is not None else [2.67, 2.25, 2.6, 2.09, 1.97, 1.61, 1.61]) + if side == "R" and qmin is None: + lo, hi = lo.copy(), hi.copy() + lo[1], hi[1] = -2.25, 1.58 + target = np.asarray(target, float) + + def err(qq): + p, R = fk(qq, side, tip) + e = [p - target] + if Rtarget is not None: + dR = Rtarget @ R.T + w = np.array([dR[2, 1] - dR[1, 2], dR[0, 2] - dR[2, 0], dR[1, 0] - dR[0, 1]]) * 0.5 + e.append(-w * wrot) + if axes_only: + for la, wd in axes_only: + e.append((R @ np.asarray(la) - np.asarray(wd)) * wrot) + if np.any(np.asarray(reg) > 0): + e.append((qq - (q0 if qref is None else np.asarray(qref))) * reg) + return np.concatenate(e) + + for _ in range(iters): + e = err(q) + J = np.zeros((len(e), 7)) + for j in range(7): + dq = np.zeros(7) + dq[j] = 1e-5 + J[:, j] = (err(q + dq) - e) / 1e-5 + lam = 1e-3 + dq = -np.linalg.solve(J.T @ J + lam * np.eye(7), J.T @ e) + q = np.clip(q + np.clip(dq, -0.3, 0.3), lo, hi) + return q, err(q) diff --git a/policies/sandwich_remove/opus-s3/policy.py b/policies/sandwich_remove/opus-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b53ff6dc56e97e768581ca693c18f55b293e5bba --- /dev/null +++ b/policies/sandwich_remove/opus-s3/policy.py @@ -0,0 +1,709 @@ +"""Policy: move the sandwich from the frying pan onto the chopping board with the spatula. + +Hand-written control: a scripted sequence of phases, closed-loop on the pelvis pose +for walking and on the head / wrist cameras for locating the objects. +""" + +import numpy as np + +from camera import pixel_to_plane_world, world_to_torso, torso_to_world, torso_pose +from g1kin import fk, ik +from vision import largest_cc, orange_mask, wood_mask, yellow_mask + +TIP = (0.13, 0.0, 0.0) +READY_L = np.array([-0.6, 0.1, 0, -0.3, 0, 0, 0]) +READY_R = np.array([-0.6, -0.1, 0, -0.3, 0, 0, 0]) +Z_HANDLE = 0.89 # world height of the spatula handle end +Z_PAN_HANDLE = 0.92 # world height of the frying-pan handle +Z_BOARD = 0.88 +Z_SANDWICH = 0.91 +TEST = "pan" +TILTTEST = True +PAN_U = 55.0 +POUR_YAW = -0.35 +TILT_DEG = 60 +POUR_BACK = 0.0 +POUR_Z = 1.02 +OBSERVE = True +LIFT = 0.08 # lift of the spatula with the sandwich on it +CARRY_V = 0.15 +LOWER = 0.07 +ROLL = 1.2 + + +def wrap(a): + return (a + np.pi) % (2 * np.pi) - np.pi + + +class Policy: + def reset(self, obs, tools): + self.tools = tools + self.obs = obs + hold = np.asarray(tools.hold_action(), dtype=np.float64) + self.qL = hold[5:12].copy() + self.qR = hold[12:19].copy() + self.gL = 0.0 + self.gR = 0.0 + self.base = np.zeros(5) + self.base[2] = 0.74 + self.log = [] + self.snap = None + self.finished = False + self.wr = {"L": False, "R": False} + self.station = None + self.keep = False + self.fpose = None + self.st_active = False + self.gen = self.script() + + # ------------------------------------------------------------------ utils + @property + def lo(self): + return self.obs["low_dim_obs"] + + def pose(self): + lo = self.lo + return lo[21], lo[22], lo[24] + + def compose(self): + a = np.zeros(21) + a[0:5] = self.base + a[5:12] = self.qL + a[12:19] = self.qR + a[19] = self.gL + a[20] = self.gR + return a + + def keep_station(self): + """Small corrective steps toward self.station while the script is not walking.""" + x, y, yaw = self.pose() + f = np.array([x, y, yaw], float) + self.fpose = f if self.fpose is None else 0.9 * self.fpose + 0.1 * f + sx, sy, syaw = self.station + ex, ey = sx - self.fpose[0], sy - self.fpose[1] + c, s = np.cos(self.fpose[2]), np.sin(self.fpose[2]) + bx, by = c * ex + s * ey, -s * ex + c * ey + d = np.hypot(bx, by) + if d > 0.03: + self.st_active = True + elif d < 0.012: + self.st_active = False + if self.st_active: + v = np.array([bx, by]) / max(d, 1e-6) * 0.08 + self.base[0], self.base[1] = v + else: + self.base[0] = self.base[1] = 0.0 + eyaw = wrap(syaw - self.fpose[2]) + self.base[3] = np.clip(1.5 * eyaw, -0.3, 0.3) if abs(eyaw) > 0.04 else 0.0 + + def act(self, obs, tools): + self.obs = obs + if self.station is not None: + self.keep_station() + try: + next(self.gen) + except StopIteration: + self.finished = True + self.base[0:2] = 0 + self.base[3] = 0 + return self.compose() + + def wait(self, n): + for _ in range(n): + yield + + def move_arms(self, qL=None, qR=None, n=40): + """Joint-space linear interpolation.""" + L0, R0 = self.qL.copy(), self.qR.copy() + for i in range(1, n + 1): + s = i / n + s = s * s * (3 - 2 * s) + if qL is not None: + self.qL = L0 + (np.asarray(qL) - L0) * s + if qR is not None: + self.qR = R0 + (np.asarray(qR) - R0) * s + yield + + def solve(self, side, p, axes, q0, wristreg=None): + if wristreg is None: + wristreg = self.wr[side] + if wristreg: + reg = np.array([0.005, 0.005, 0.005, 0.005, 0.0, 0.1, 0.1]) + q, e = ik(p, q0, side, tip=TIP, axes_only=axes, reg=reg, qref=np.r_[q0[:5], 0, 0], iters=40, wrot=0.3) + else: + q, e = ik(p, q0, side, tip=TIP, axes_only=axes, reg=0.005, iters=40, wrot=0.3) + return q, e + + def cart_move(self, side, p1, axes, n=40): + """Straight-line move of the tool tip (torso frame) with fixed orientation axes.""" + q = (self.qL if side == "L" else self.qR).copy() + p0, _ = fk(q, side, TIP) + p1 = np.asarray(p1, float) + for i in range(1, n + 1): + s = i / n + s = s * s * (3 - 2 * s) + q, _ = self.solve(side, p0 + (p1 - p0) * s, axes, q) + if side == "L": + self.qL = q + else: + self.qR = q + yield + + def cart_move_world(self, side, pw, axes, n=40): + pt = world_to_torso(np.asarray(pw, float), self.lo) + yield from self.cart_move(side, pt, axes, n) + + def walk_to(self, x, y, yaw, tol=0.025, ytol=0.04, max_steps=300, vmax=0.25): + stable = 0 + self.station = None + f = np.array(self.pose(), dtype=float) + for _ in range(max_steps): + f = 0.85 * f + 0.15 * np.array(self.pose()) + px, py, pyaw = f + ex, ey = x - px, y - py + c, s = np.cos(pyaw), np.sin(pyaw) + bx, by = c * ex + s * ey, -s * ex + c * ey + eyaw = wrap(yaw - pyaw) + dist = np.hypot(bx, by) + if dist < tol and abs(eyaw) < ytol: + stable += 1 + self.base[0] = self.base[1] = self.base[3] = 0 + if stable > 5: + break + yield + continue + stable = 0 + v = np.array([bx, by]) * 1.5 + sp = np.linalg.norm(v) + if sp > vmax: + v *= vmax / sp + if dist >= tol and sp < 0.07: + v *= 0.07 / max(sp, 1e-6) + if dist < tol: + v[:] = 0 + self.base[0], self.base[1] = v + self.base[3] = np.clip(2.0 * eyaw, -0.5, 0.5) if abs(eyaw) > 0.5 * ytol else 0.0 + yield + self.base[0] = self.base[1] = self.base[3] = 0 + self.station = (x, y, yaw) if self.keep else None + self.fpose = None + self.st_active = False + + def set_q(self, side, q): + if side == "L": + self.qL = q + else: + self.qR = q + + def get_q(self, side): + return (self.qL if side == "L" else self.qR).copy() + + def servo_handle(self, side, p, axes, depth, cam, uv_t=(42.0, 30.0), iters=14, gain=0.5): + """Advance along the gripper axis by `depth` while centring the orange handle end + in the wrist camera (image right = -y_gripper, image up = +z_gripper).""" + p = np.asarray(p, float).copy() + step = depth / iters + q = self.get_q(side) + for it in range(iters): + _, R = fk(q, side, TIP) + im = self.tools.image(cam) + m = orange_mask(im) + ys, xs = np.nonzero(m) + du = dv = 0.0 + if len(ys) > 8: + vtop = ys.min() + sel = ys <= vtop + 8 + u = xs[sel].mean() + du, dv = u - uv_t[0], vtop - uv_t[1] + self.log.append(("servo", it, round(u, 1), int(vtop), len(ys))) + k = 0.0025 * gain + d = np.array([step, -k * du, -k * dv]) + p1 = p + R @ d + for i in range(1, 9): + q, _ = self.solve(side, p + (p1 - p) * i / 8, axes, q) + self.set_q(side, q) + yield + p = p1 + yield from self.wait(4) + self.servo_p = p + + # ------------------------------------------------------------ perception + def find_handle_end(self): + im = self.tools.image("head") + m = orange_mask(im) + ys, xs = np.nonzero(m) + if len(ys) < 5: + return None + vmax = ys.max() + u = xs[ys >= vmax - 1].mean() + return pixel_to_plane_world(u, vmax + 0.5, self.lo, Z_HANDLE) + + def find_pan_handle(self): + """Dark pan handle overhanging the floor left of the hob cabinet -> world line x = a*y + b.""" + im = self.tools.image("head") + dm = im.astype(int).max(-1) < 60 + dm[30:] = False + ys, xs = np.nonzero(dm) + pts = [] + for u, v in zip(xs, ys): + w = pixel_to_plane_world(u + 0.5, v + 0.5, self.lo, Z_PAN_HANDLE) + if 0.31 < w[1] < 0.65 and 0.5 < w[0] < 0.85: + pts.append(w) + if len(pts) < 6: + return None + pts = np.array(pts) + A = np.stack([pts[:, 1], np.ones(len(pts))], 1) + sol, *_ = np.linalg.lstsq(A, pts[:, 0], rcond=None) + return sol, pts[:, 1].min(), pts[:, 1].max() + + def find_board(self): + im = self.tools.image("head") + m = largest_cc(wood_mask(im)) + ys, xs = np.nonzero(m) + if len(ys) < 20: + return None + P = np.array([pixel_to_plane_world(u + 0.5, v + 0.5, self.lo, Z_BOARD) for u, v in zip(xs, ys)]) + return dict(xmin=np.percentile(P[:, 0], 3), xmax=np.percentile(P[:, 0], 97), + ymin=np.percentile(P[:, 1], 3), ymax=np.percentile(P[:, 1], 97), n=len(P), + top=ys.min(), right=xs.max(), left=xs.min()) + + def find_sandwich(self): + im = self.tools.image("head") + m = yellow_mask(im) + m[25:] = False + ys, xs = np.nonzero(m) + if len(ys) < 10: + return None + return pixel_to_plane_world(xs.mean() + 0.5, ys.mean() + 0.5, self.lo, Z_SANDWICH) + + def find_pan_handle_close(self): + """Pan handle seen from beside the cabinet (dark on the blue floor) -> (a, b) of x = a*y + b.""" + im = self.tools.image("head") + dm = im.astype(int).max(-1) < 50 + ys, xs = np.nonzero(dm) + pts = [] + for u, v in zip(xs, ys): + w = pixel_to_plane_world(u + 0.5, v + 0.5, self.lo, Z_PAN_HANDLE) + if 0.31 < w[1] < 0.65 and 0.5 < w[0] < 0.9: + pts.append(w) + if len(pts) < 6: + return None + pts = np.array(pts) + A = np.stack([pts[:, 1], np.ones(len(pts))], 1) + sol, *_ = np.linalg.lstsq(A, pts[:, 0], rcond=None) + self.log.append(("close_pts", len(pts), pts[:, 1].min(), pts[:, 1].max())) + return sol + + # ---------------------------------------------------------------- script + def script(self): + yield from self.test_pan2() + + def script_spat(self): + yield from self.move_arms(READY_L, READY_R, 40) + self.base[4] = -0.2 + x0, y0, _ = self.pose() + yield from self.walk_to(x0 + 0.12, y0, 0.0) + yield from self.wait(20) + h = self.find_handle_end() + sand = self.find_sandwich() + self.log.append(("obs", h, sand, self.pose())) + self.base[4] = 0.0 + if h is None: + return + yield from self.walk_to(h[0] - 0.36, h[1] + 0.15, 0.0) + yield from self.wait(20) + h2 = self.find_handle_end() + if h2 is not None: + h = h2 + ht = world_to_torso(h, self.lo) + self.log.append(("handle_torso", ht, self.pose())) + axes = [((1, 0, 0), np.array([1, 0, -1]) / np.sqrt(2)), ((0, 1, 0), np.array([0, -1.0, 0]))] + grasp = ht + np.array([0.03, 0, -0.005]) + pre = grasp + np.array([-0.07, 0, 0.07]) + q, e = self.solve("R", pre, axes, np.array([-0.922, -1.012, 0.632, -0.166, -1.028, -0.783, 1.172])) + yield from self.move_arms(None, q, 60) + yield from self.wait(20) + yield from self.servo_handle("R", pre, axes, np.linalg.norm(grasp - pre) + 0.01, "right_wrist") + yield from self.wait(10) + self.snap = "grasp" + yield + self.gR = 1.0 + yield from self.wait(30) + hand_w0 = torso_to_world(fk(self.qR, "R", TIP)[0], self.lo) + d_sand = (sand - hand_w0) if sand is not None else np.array([0.07, 0.0, 0.0]) + self.log.append(("d_sand", d_sand)) + yield from self.cart_move("R", self.servo_p + np.array([0, 0, LIFT]), axes, 60) + yield from self.wait(20) + self.snap = "lift" + yield + # ---- carry sideways to the board + hand_t = fk(self.qR, "R", TIP)[0] + px, py, _ = self.pose() + yield from self.walk_to(px - 0.05, py, 0.0, vmax=CARRY_V) + yield from self.walk_to(px - 0.05, -0.30, 0.0, vmax=CARRY_V) + yield from self.wait(20) + self.snap = "atboard" + yield + bd = self.find_board() + self.log.append(("board", bd, self.pose())) + if bd is None: + bcx, bcy = 0.62, -0.53 + else: + bcx, bcy = bd["xmin"] + 0.10, 0.5 * (bd["ymin"] + bd["ymax"]) + # pelvis -> hand offset in world (yaw ~ 0) + hw = torso_to_world(hand_t, self.lo) + x, y, _ = self.pose() + off = hw[:2] - np.array([x, y]) + tx, ty = np.array([bcx, bcy]) - d_sand[:2] - off + self.log.append(("carry_target", tx, ty)) + self.keep = True + yield from self.walk_to(tx, ty, 0.0, vmax=CARRY_V) + yield from self.wait(20) + self.snap = "over" + yield + # ---- lower onto the board, then roll the spatula so the sandwich slides off + cur = fk(self.qR, "R", TIP)[0] + yield from self.cart_move("R", cur + np.array([0, 0, -LOWER]), axes, 50) + yield from self.wait(20) + self.snap = "low" + yield + q0 = self.qR.copy() + for k in range(1, 61): + q = q0.copy() + q[4] = np.clip(q0[4] + ROLL * k / 60, -1.97, 1.97) + self.qR = q + yield + yield from self.wait(30) + self.snap = "rolled" + yield + cur = fk(self.qR, "R", TIP)[0] + _, Rc = fk(self.qR, "R", TIP) + ax2 = [((1, 0, 0), Rc[:, 0]), ((0, 1, 0), Rc[:, 1])] + yield from self.cart_move("R", cur + np.array([-0.12, 0, 0.0]), ax2, 50) + yield from self.cart_move("R", cur + np.array([-0.12, 0, 0.10]), ax2, 40) + self.keep = False + self.base[4] = -0.1 + yield from self.wait(60) + self.snap = "after" + yield + yield from self.wait(100) + + def test_pan(self): + yield from self.move_arms(READY_L, READY_R, 40) + self.base[4] = -0.2 + x0, y0, _ = self.pose() + yield from self.walk_to(x0 + 0.12, y0, 0.0) + yield from self.wait(20) + self.pan_handle = self.find_pan_handle() + sand = self.find_sandwich() + self.base[4] = 0.0 + (a, b), _, _ = self.pan_handle + YG = 0.36 + gw = np.array([a * YG + b, YG, Z_PAN_HANDLE]) + d_sand = sand - gw + self.log.append(("gw", gw, "sand", sand)) + yield from self.walk_to(0.15, YG + 0.12, 0.0) + yield from self.walk_to(gw[0] - 0.32, YG + 0.12, 0.0) + yield from self.wait(20) + g = world_to_torso(gw, self.lo) + self.log.append(("g", g, self.pose())) + ax = [((1, 0, 0), np.array([1.0, 0, 0])), ((0, 1, 0), np.array([0, 0, 1.0]))] + pre = g + np.array([-0.10, 0, 0]) + q, e = self.solve("R", pre, ax, np.array([0.092, 0.228, 0.046, -0.569, 1.364, 0.104, -0.477])) + self.log.append(("pre", q, e)) + yield from self.move_arms(None, q, 60) + yield from self.wait(20) + self.snap = "pre" + yield + yield from self.cart_move("R", pre + np.array([0, 0, 0.03]), ax, 15) + yield from self.wait(10) + self.snap = "pz" + yield + yield from self.cart_move("R", pre + np.array([0, 0.03, 0]), ax, 15) + yield from self.wait(10) + self.snap = "py" + yield + yield from self.cart_move("R", pre, ax, 15) + yield from self.cart_move("R", g + np.array([0.02, 0, 0]), ax, 40) + yield from self.wait(10) + self.snap = "at" + yield + self.gR = 1.0 + yield from self.wait(30) + yield from self.cart_move("R", g + np.array([-0.02, 0, 0.08]), ax, 40) + yield from self.wait(30) + self.snap = "lift" + yield + yield from self.cart_move("R", g + np.array([-0.04, 0, 0.14]), ax, 40) + if TILTTEST: + px, py, _ = self.pose() + yield from self.walk_to(px - 0.1, py, 0.0) + yield from self.cart_move("R", np.array([0.28, 0.08, 0.17]), ax, 40) + yield from self.wait(30) + self.snap = "t0" + yield + for k in range(1, 61): + th = np.radians(90) * k / 60 + axk = [((1, 0, 0), np.array([1.0, 0, 0])), ((0, 1, 0), np.array([0, -np.sin(th), np.cos(th)]))] + q, _ = self.solve("R", np.array([0.28, 0.08, 0.17]), axk, self.qR) + self.qR = q + yield from self.wait(2) + if k % 15 == 0: + self.snap = f"t{k}" + yield from self.wait(40) + self.snap = "tend" + yield + return + px, py, _ = self.pose() + yield from self.walk_to(px - 0.15, py, 0.0) + self.snap = "back" + yield + yield from self.walk_to(px - 0.15, py - 0.4, 0.0) + self.snap = "side1" + yield + yield from self.walk_to(0.15, -0.40, 0.0) + self.base[4] = -0.2 + yield from self.wait(40) + self.snap = "side2" + yield + bd = self.find_board() + self.log.append(("board", bd)) + gx = 0.60 - d_sand[0] + gy = bd["ymax"] + 0.26 + self.log.append(("grip_target", gx, gy)) + self.base[4] = 0.0 + yield from self.walk_to(0.22, gy - 0.02, 0.0) + yield from self.wait(20) + yield from self.cart_move_world("R", (gx, gy, 1.02), ax, 60) + yield from self.wait(20) + self.snap = "over" + yield + yield from self.cart_move_world("R", (gx, gy, 0.95), ax, 30) + yield from self.wait(20) + self.snap = "touch" + yield + yield from self.cart_move_world("R", (gx, gy - 0.04, 1.06), ax, 50) + yield from self.wait(20) + self.snap = "tilt1" + yield + yield from self.cart_move_world("R", (gx, gy - 0.07, 1.15), ax, 50) + yield from self.wait(40) + self.snap = "tilt" + yield + yield from self.wait(30) + yield from self.cart_move_world("R", (gx - 0.08, gy + 0.15, 1.1), ax, 40) + yield from self.walk_to(0.2, -0.5, 0.0) + self.base[4] = -0.2 + yield from self.wait(40) + self.snap = "after" + yield + yield from self.wait(60) + + def test_pan2(self): + yield from self.move_arms(READY_L, READY_R, 40) + self.base[4] = -0.2 + x0, y0, _ = self.pose() + yield from self.walk_to(x0 + 0.12, y0, 0.0) + yield from self.wait(20) + self.pan_handle = self.find_pan_handle() + sand = self.find_sandwich() + self.base[4] = 0.0 + (a, b), _, _ = self.pan_handle if self.pan_handle is not None else ((-0.34, 0.79), 0, 0) + YG = 0.36 + gw = np.array([a * YG + b, YG, Z_PAN_HANDLE]) + d_sand = (sand - gw) if sand is not None else np.array([0.0, -0.19, 0.0]) + if np.linalg.norm(d_sand[:2] - np.array([0.0, -0.19])) > 0.08: + d_sand = np.array([0.0, -0.19, 0.0]) + self.log.append(("gw", gw, "sand", sand)) + self.d_pan = d_sand + # look at the board first, with nothing in the hands + yield from self.walk_to(0.15, -0.40, 0.0) + self.base[4] = -0.2 + yield from self.wait(40) + self.board = self.find_board() + if self.board is None or self.board["n"] < 200: + self.board = dict(xmin=0.52, xmax=0.72, ymin=-0.63, ymax=-0.43, n=0) + self.log.append(("board_clean", self.board)) + self.snap = "board" + self.base[4] = 0.0 + yield + yield from self.grasp_pan(gw) + yield from self.carry_and_pour(d_sand) + + def grasp_pan(self, gw): + yield from self.walk_to(0.15, gw[1] + 0.12, 0.0) + yield from self.walk_to(gw[0] - 0.32, gw[1] + 0.12, 0.0) + yield from self.wait(20) + g = world_to_torso(gw, self.lo) + self.log.append(("g", g, self.pose())) + ax = [((1, 0, 0), np.array([1.0, 0, 0])), ((0, 1, 0), np.array([0, 0, 1.0]))] + self.axR = ax + pre = g + np.array([-0.10, 0, 0]) + q, e = self.solve("R", pre, ax, np.array([0.092, 0.228, 0.046, -0.569, 1.364, 0.104, -0.477])) + self.log.append(("pre", q, e)) + yield from self.move_arms(None, q, 60) + yield from self.wait(15) + # this probing sequence before the approach is what grasped reliably in tests + yield from self.cart_move("R", pre + np.array([0, 0, 0.03]), ax, 15) + yield from self.wait(10) + yield from self.cart_move("R", pre + np.array([0, 0.03, 0]), ax, 15) + yield from self.wait(10) + yield from self.cart_move("R", pre, ax, 15) + yield from self.cart_move("R", g + np.array([0.02, 0, 0]), ax, 40) + yield from self.wait(10) + self.snap = "at" + yield + self.gR = 1.0 + yield from self.wait(30) + yield from self.cart_move("R", g + np.array([-0.03, 0, 0.08]), ax, 40) + yield from self.wait(20) + self.snap = "lift" + yield + + def carry_and_pour(self, d_sand): + ax = self.axR + px, py, _ = self.pose() + yield from self.walk_to(px - 0.15, py, 0.0) + bd = self.board + bcx, bcy = 0.5 * (bd["xmin"] + bd["xmax"]), 0.5 * (bd["ymin"] + bd["ymax"]) + # pan centre over the +y half of the board; it slides off towards -y when tipped + psi = POUR_YAW + c, s = np.cos(psi), np.sin(psi) + Rz = np.array([[c, -s], [s, c]]) + dw = Rz @ self.d_pan[:2] + hx, hy = np.array([bcx, bcy]) - POUR_BACK * np.array([c, s]) - dw + rx, ry = np.array([hx, hy]) - Rz @ np.array([0.42, 0.0]) + self.log.append(("hand_target", hx, hy, "robot", rx, ry)) + self.base[4] = 0.0 + self.keep = True + yield from self.walk_to(rx, ry, psi) + yield from self.wait(20) + yield from self.cart_move_world("R", (hx, hy, POUR_Z), ax, 60) + if OBSERVE: + eye = np.array([0.2, 0.2, 0.38]) + bt = world_to_torso(np.array([bcx, bcy, 0.9]), self.lo) + dv = (bt - eye) / np.linalg.norm(bt - eye) + qe, _ = ik(eye, self.qL, "L", tip=TIP, axes_only=[((1, 0, 0), dv)], reg=0.01, iters=200) + yield from self.move_arms(qe, None, 40) + yield from self.wait(30) + self.snap = "over" + yield + q0 = self.qR.copy() + p_hand, _ = fk(self.qR, "R", TIP) + for k in range(1, 61): + th = np.radians(TILT_DEG) * k / 60 + axk = [((1, 0, 0), np.array([np.cos(th), 0, -np.sin(th)])), ((0, 1, 0), np.array([np.sin(th), 0, np.cos(th)]))] + self.qR, _ = self.solve("R", p_hand, axk, self.qR) + yield from self.wait(2) + if k % 15 == 0: + self.snap = f"r{k}" + yield from self.wait(60) + self.snap = "poured" + yield + yield from self.move_arms(None, q0, 40) + cur = fk(self.qR, "R", TIP)[0] + yield from self.cart_move("R", cur + np.array([0.0, 0.0, 0.10]), ax, 30) + yield from self.cart_move("R", cur + np.array([-0.12, -0.22, 0.10]), ax, 50) + self.keep = False + px, py, _ = self.pose() + yield from self.walk_to(px - 0.1, py - 0.1, -0.6) + self.base[4] = -0.2 + yield from self.wait(40) + self.snap = "after" + yield + yield from self.wait(60) + + def script_full(self): + yield from self.move_arms(READY_L, READY_R, 40) + self.base[4] = -0.2 + x0, y0, _ = self.pose() + yield from self.walk_to(x0 + 0.12, y0, 0.0) + yield from self.wait(20) + h = self.find_handle_end() + self.pan_handle = self.find_pan_handle() + self.log.append(("obs", h, self.pan_handle, self.pose())) + self.base[4] = 0.0 + if h is None: + return + yield from self.walk_to(h[0] - 0.36, h[1] + 0.15, 0.0) + yield from self.wait(20) + yield from self.wait(20) + h = self.find_handle_end() + self.log.append(("handle3", h, self.pose())) + ht = world_to_torso(h, self.lo) + self.log.append(("handle_torso", ht)) + axes = [((1, 0, 0), np.array([1, 0, -1]) / np.sqrt(2)), ((0, 1, 0), np.array([0, -1.0, 0]))] + grasp = ht + np.array([0.03, 0, -0.005]) + pre = grasp + np.array([-0.07, 0, 0.07]) + q, e = self.solve("R", pre, axes, np.array([-0.922, -1.012, 0.632, -0.166, -1.028, -0.783, 1.172])) + self.log.append(("pre_ik", q, e)) + yield from self.move_arms(None, q, 60) + yield from self.wait(20) + self.snap = "pre" + yield + yield from self.servo_handle("R", pre, axes, np.linalg.norm(grasp - pre) + 0.01, "right_wrist") + yield from self.wait(10) + self.snap = "grasp" + yield + self.gR = 1.0 + yield from self.wait(30) + yield from self.cart_move("R", self.servo_p + np.array([0, 0, 0.12]), axes, 50) + yield from self.wait(20) + self.snap = "lift" + yield + yield from self.cart_move("R", self.servo_p + np.array([-0.05, -0.05, 0.2]), axes, 50) + # ---- pan handle (test) + px, py, _ = self.pose() + (a, b), _, _ = self.pan_handle + YG = 0.37 + gw = np.array([a * YG + b, YG, Z_PAN_HANDLE]) + psi = -0.35 + c, s = np.cos(psi), np.sin(psi) + bx, by = gw[0] - (c * 0.38), gw[1] - (s * 0.38) + yield from self.walk_to(0.15, py, 0.0) + yield from self.walk_to(0.15, by, psi) + yield from self.walk_to(bx, by, psi) + yield from self.wait(20) + self.snap = "B" + yield + ph = self.find_pan_handle_close() + self.log.append(("pan_handle_close", ph)) + if ph is not None: + (a, b) = ph + gw = np.array([a * YG + b, YG, Z_PAN_HANDLE]) + g = world_to_torso(gw, self.lo) + self.log.append(("pan_grasp_torso", g, self.pose())) + _, Rt = torso_pose(self.lo) + ap = np.array([c, s, -1.0]) / np.sqrt(2) + hd = np.array([a, 1.0, 0.0]) / np.hypot(a, 1.0) + fd = np.cross(ap, hd) + fd /= np.linalg.norm(fd) + if fd[2] > 0: + fd = -fd + axL = [((1, 0, 0), Rt.T @ ap), ((0, 1, 0), Rt.T @ fd)] + pre = g - Rt.T @ ap * 0.1 + q, e = self.solve("L", pre, axL, np.array([-0.935, -0.970, 0.344, 0.154, -0.542, -0.186, 1.318])) + self.log.append(("Lpre_ik", q, e)) + yield from self.move_arms(q, None, 60) + yield from self.wait(20) + self.snap = "Lpre" + yield + _, R = fk(q, "L", TIP) + yield from self.cart_move("L", pre + R @ np.array([0, 0.02, 0]), axL, 15) + yield from self.wait(10) + self.snap = "Ly" + yield + yield from self.cart_move("L", pre + R @ np.array([0, 0, 0.02]), axL, 15) + yield from self.wait(10) + self.snap = "Lz" + yield + yield from self.cart_move("L", g + R @ np.array([0.015, 0, 0]), axL, 40) + yield from self.wait(10) + self.snap = "Lgrasp" + yield + self.gL = 1.0 + yield from self.wait(30) + yield from self.cart_move("L", g + np.array([-0.03, 0, 0.1]), axL, 50) + yield from self.wait(30) + self.snap = "Llift" + yield diff --git a/policies/sandwich_remove/opus-s3/vision.py b/policies/sandwich_remove/opus-s3/vision.py new file mode 100644 index 0000000000000000000000000000000000000000..4d10d3e6a751f9ea67a88da48976e38e104537e3 --- /dev/null +++ b/policies/sandwich_remove/opus-s3/vision.py @@ -0,0 +1,34 @@ +"""Colour segmentation helpers for the head / wrist cameras.""" +import numpy as np + + +def orange_mask(im): + im = im.astype(int) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + return (r > 150) & (g > 50) & (g < 150) & (b < 70) & (r - g > 70) + + +def yellow_mask(im): + im = im.astype(int) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + return (r > 190) & (g > 150) & (r - b > 60) + + +def wood_mask(im): + im = im.astype(int) + r, g, b = im[..., 0], im[..., 1], im[..., 2] + return (r > 170) & (g > 120) & (b < 175) & (r - b > 75) + + +def largest_cc(m): + import cv2 + + n, lab, st, _ = cv2.connectedComponentsWithStats(m.astype(np.uint8)) + if n <= 1: + return np.zeros_like(m, bool) + i = 1 + int(np.argmax(st[1:, 4])) + return lab == i + + +def dark_mask(im, thr=45): + return im.astype(int).max(-1) < thr diff --git a/policies/saucepan_to_hob/astra-s1/episodes.csv b/policies/saucepan_to_hob/astra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..52c4a806f417347e3397963463bf71c285ca7ce2 --- /dev/null +++ b/policies/saucepan_to_hob/astra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4650,timeout,0 +620001,0,4650,timeout,0 +620002,0,4650,timeout,0 +620003,1,3929,success,0 +620004,1,4163,success,0 +620005,0,4650,timeout,0 +620006,0,4650,timeout,0 +620007,0,4650,timeout,0 +620008,0,4650,timeout,0 +620009,0,4650,timeout,0 +620010,1,4328,success,0 +620011,0,4650,timeout,0 +620012,0,4650,timeout,0 +620013,1,4083,success,0 +620014,0,4650,timeout,0 +620015,0,4650,timeout,0 +620016,0,4650,timeout,0 +620017,0,4650,timeout,0 +620018,0,4650,timeout,0 +620019,0,4650,timeout,0 +620020,0,4650,timeout,0 +620021,1,4188,success,0 +620022,0,4650,timeout,0 +620023,0,4650,timeout,0 +620024,0,4650,timeout,0 +620025,0,4650,timeout,0 +620026,0,4650,timeout,0 +620027,1,4187,success,0 +620028,0,4650,timeout,0 +620029,0,4650,timeout,0 +620030,0,4650,timeout,0 +620031,1,4164,success,0 +620032,0,4650,timeout,0 +620033,0,4650,timeout,0 +620034,0,4650,timeout,0 +620035,0,4650,timeout,0 +620036,1,3946,success,0 +620037,0,4650,timeout,0 +620038,0,4650,timeout,0 +620039,0,4650,timeout,0 +620040,0,4650,timeout,0 +620041,0,4650,timeout,0 +620042,0,4650,timeout,0 +620043,0,4650,timeout,0 +620044,0,4650,timeout,0 +620045,0,4650,timeout,0 +620046,0,4650,timeout,0 +620047,1,4308,success,0 +620048,1,4219,success,0 +620049,0,4650,timeout,0 +620050,0,4650,timeout,0 +620051,0,4650,timeout,0 +620052,0,4650,timeout,0 +620053,0,4650,timeout,0 +620054,0,4650,timeout,0 +620055,0,4650,timeout,0 +620056,0,4650,timeout,0 +620057,0,4650,timeout,0 +620058,0,4650,timeout,0 +620059,0,4650,timeout,0 +620060,0,4650,timeout,0 +620061,0,4650,timeout,0 +620062,0,4650,timeout,0 +620063,0,4650,timeout,0 +620064,0,4650,timeout,0 +620065,0,4650,timeout,0 +620066,0,4650,timeout,0 +620067,0,4650,timeout,0 +620068,1,3937,success,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,0,4650,timeout,0 +620073,1,4323,success,0 +620074,0,4650,timeout,0 +620075,0,4650,timeout,0 +620076,0,4650,timeout,0 +620077,0,4650,timeout,0 +620078,0,4650,timeout,0 +620079,0,4650,timeout,0 +620080,0,4650,timeout,0 +620081,0,4650,timeout,0 +620082,0,4650,timeout,0 +620083,0,4650,timeout,0 +620084,0,4650,timeout,0 +620085,0,4650,timeout,0 +620086,0,4650,timeout,0 +620087,0,4650,timeout,0 +620088,0,4650,timeout,0 +620089,0,4650,timeout,0 +620090,0,4650,timeout,0 +620091,0,4650,timeout,0 +620092,0,4650,timeout,0 +620093,0,4650,timeout,0 +620094,0,4650,timeout,0 +620095,1,4060,success,0 +620096,0,4650,timeout,0 +620097,0,4650,timeout,0 +620098,0,4650,timeout,0 +620099,1,4211,success,0 diff --git a/policies/saucepan_to_hob/astra-s1/policy.py b/policies/saucepan_to_hob/astra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..d1ac856f02d58eff759563b41d39c9b28fc5c3a5 --- /dev/null +++ b/policies/saucepan_to_hob/astra-s1/policy.py @@ -0,0 +1,102 @@ +"""Deterministic saucepan controller using proprioception and wrist-camera geometry. + +Hand-written motion phases open the door and clear the cabinet. Colour masks +and a geometric line fit align the gripper with the saucepan handle. Joint +feedback detects missed grasps; the transfer keeps the load low until clear +of the cabinet, then lowers it onto the hob before releasing it. +""" + +import numpy as np +import cv2 +from scipy.spatial.transform import Rotation as R + +class Policy: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action(),float);self.phase=0;self.start=0;self.ready=0;self.retries=0 + self.stages=[ + (100,{19:0,20:0,5:.3,6:.4,9:-.4,10:-.3,12:.6}), + (80,{0:.1}), (120,{0:0,2:.6}), (60,{19:1}), + (100,{2:.74}),(140,{0:-.12}),(50,{0:0}), + (240,{0:-.1,1:-.15,5:.6,10:-.6}), (10,{0:0,1:0}), + (220,{},(-.25,-.65,0)), + (380,{19:0,5:1.3,6:0,8:.5,9:0,10:0,12:1.3,15:.5},(-.3,.2,0)), + (80,{0:0,1:0,3:0,12:.3,15:0,17:-.3}), + (300,{},(.43,.15,0)), + (70,{0:0,1:0,3:0,14:.1,16:1.3,17:-.15}), + (250,{2:.68},(.495,.16,0)), + (80,{0:0,1:0,3:0}), + (100,{2:.62,12:.25}), + ] + def goto(self,o,x,y,yaw=0): + px,py,pz,ang=o['low_dim_obs'][21:25];dx=x-px;dy=y-py;c=np.cos(ang);s=np.sin(ang) + v=np.clip(np.array([c*dx+s*dy,-s*dx+c*dy])*1.5,-.2,.2) + for k in range(2): + if abs(v[k])<.06:v[k]=0 if abs(v[k])<.02 else np.sign(v[k])*.06 + self.a[:2]=v;self.a[3]=np.clip(2*(yaw-ang),-.4,.4) + return abs(dx)<.025 and abs(dy)<.025 and abs(ang-yaw)<.04 + def advance(self,t):self.phase+=1;self.start=t;self.ready=0 + def handle(self,tools): + im=tools.image('right_wrist');r,g,b=im.astype(float).transpose(2,0,1) + mask=(r>100)&(g>65)&(r>g*1.13)&(g>b*1.25)&(r> b*1.5) + brown=(r>65)&(g>28)&(r>g*1.2)&(g>b*1.15)&(r>b*1.5) + rows=np.where((brown.sum(axis=1)>20)&(np.arange(84)>35))[0] + bowl=float(rows[0]) if len(rows) else 90. + mask[60:]=False + ys,xs=np.where(mask) + if len(xs)<25:return None + # A long, narrow, gold handle in the upper part of the wrist view. + pts=[] + for y in range(5,55): + xx=np.where(mask[y])[0] + if 2<=len(xx)<=25:pts.append((y,float(np.median(xx)))) + if len(pts)<12:return None + pts=np.array(pts,dtype=np.float32);vy,vx,y0,x0=cv2.fitLine(pts,cv2.DIST_L1,0,.01,.01).ravel();slope=vx/(vy+1e-8);intercept=x0-slope*y0 + return slope*30+intercept,slope,bowl + def act(self,obs,tools): + t=obs['t'];dt=t-self.start;n=len(self.stages) + if self.phase2:self.goto(obs,*stage[2]) + if dt>=dur:self.advance(t) + elif self.phase==n: + if dt%8==0: + h=self.handle(tools) + if h is not None: + x,slope,bowl=h + self.a[14]=np.clip(self.a[14]+np.clip((bowl-60)*.001,-.008,.008),-.1,.5) + self.a[2]=np.clip(self.a[2]+np.clip((42-x)*.00065,-.008,.008),.56,.69) + self.a[16]=np.clip(self.a[16]-np.clip(slope*.07,-.018,.018),.8,1.8) + if abs(x-42)<3 and abs(bowl-60)<8:self.ready+=1 + else:self.ready=0 + if self.ready>=5 or dt>240:self.a[20]=1;self.advance(t) + elif self.phase==n+1: + if dt>70: + if obs['low_dim_obs'][51]>.96 and self.retries<3: + self.retries+=1;self.a[20]=0 + self.a[12]-=.035;self.a[2]-=.01 + self.phase=n;self.start=t;self.ready=0 + else: + self.grasp=self.a.copy();self.advance(t) + elif self.phase==n+2: + self.a[2]=min(max(.61,min(.66,self.grasp[2]+.03)),self.grasp[2]+dt*.0007) + if dt>110:self.advance(t) + elif self.phase==n+3: + self.goto(obs,-.20,.12,0) + if dt>310: + self.a[:2]=0;self.a[3]=0;self.lift0=self.a.copy();self.advance(t) + elif self.phase==n+4: + self.a[2]=min(.74,.66+dt*.001) + frac=min(1,max(0,dt-80)/240); old=self.lift0;new_s=old[12]-.9*frac + # Raise the arm only after the saucepan clears the cabinet. + self.a[12]=new_s + if dt>360:self.advance(t) + elif self.phase==n+5: + self.goto(obs,.44,.18,0) + if dt>290:self.a[:2]=0;self.a[3]=0;self.advance(t) + elif self.phase==n+6: + frac=min(1,dt/240);old=self.lift0 + rot=R.from_euler('z',-old[14])*R.from_euler('y',.9*frac)*R.from_euler('z',old[14])*R.from_euler('XYZ',old[16:19]) + self.a[16:19]=rot.as_euler('XYZ') + if dt>260:self.a[20]=0;self.advance(t) + return self.a.copy() diff --git a/policies/saucepan_to_hob/astra-s2/episodes.csv b/policies/saucepan_to_hob/astra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..72146d263db62f262f838409fbb0c0fcc45a93a0 --- /dev/null +++ b/policies/saucepan_to_hob/astra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4650,timeout,0 +620001,0,4650,timeout,0 +620002,0,4650,timeout,0 +620003,1,4107,success,0 +620004,0,4650,timeout,0 +620005,0,4650,timeout,0 +620006,1,4233,success,0 +620007,0,4650,timeout,0 +620008,0,4650,timeout,0 +620009,0,4650,timeout,0 +620010,0,4650,timeout,0 +620011,0,4650,timeout,0 +620012,0,4650,timeout,0 +620013,0,4650,timeout,0 +620014,0,4650,timeout,0 +620015,0,4650,timeout,0 +620016,1,4077,success,0 +620017,0,4650,timeout,0 +620018,1,4051,success,0 +620019,0,4650,timeout,0 +620020,1,4136,success,0 +620021,0,4650,timeout,0 +620022,0,4650,timeout,0 +620023,0,4650,timeout,0 +620024,0,4650,timeout,0 +620025,0,4650,timeout,0 +620026,0,4650,timeout,0 +620027,0,4650,timeout,0 +620028,1,4108,success,0 +620029,0,4650,timeout,0 +620030,0,4650,timeout,0 +620031,0,4650,timeout,0 +620032,0,4650,timeout,0 +620033,0,4650,timeout,0 +620034,0,4650,timeout,0 +620035,0,4650,timeout,0 +620036,1,4134,success,0 +620037,0,4650,timeout,0 +620038,0,4650,timeout,0 +620039,0,4650,timeout,0 +620040,0,4650,timeout,0 +620041,0,4650,timeout,0 +620042,0,4650,timeout,0 +620043,0,4650,timeout,0 +620044,0,4650,timeout,0 +620045,0,4650,timeout,0 +620046,0,4650,timeout,0 +620047,0,4650,timeout,0 +620048,0,4650,timeout,0 +620049,1,4134,success,0 +620050,0,4650,timeout,0 +620051,0,4650,timeout,0 +620052,0,4650,timeout,0 +620053,0,4650,timeout,0 +620054,1,4063,success,0 +620055,0,4650,timeout,0 +620056,0,4650,timeout,0 +620057,0,4650,timeout,0 +620058,0,4650,timeout,0 +620059,0,4650,timeout,0 +620060,1,4101,success,0 +620061,0,4650,timeout,0 +620062,0,4650,timeout,0 +620063,0,4650,timeout,0 +620064,0,4650,timeout,0 +620065,0,4650,timeout,0 +620066,0,4650,timeout,0 +620067,0,4650,timeout,0 +620068,1,4100,success,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,1,4129,success,0 +620073,0,4650,timeout,0 +620074,0,4650,timeout,0 +620075,0,4650,timeout,0 +620076,0,4650,timeout,0 +620077,0,4650,timeout,0 +620078,0,4650,timeout,0 +620079,0,4650,timeout,0 +620080,0,4650,timeout,0 +620081,0,4650,timeout,0 +620082,0,4650,timeout,0 +620083,0,4650,timeout,0 +620084,1,4060,success,0 +620085,0,4650,timeout,0 +620086,0,4650,timeout,0 +620087,0,4650,timeout,0 +620088,1,4059,success,0 +620089,0,4650,timeout,0 +620090,1,4134,success,0 +620091,0,4650,timeout,0 +620092,0,4650,timeout,0 +620093,0,4650,timeout,0 +620094,0,4650,timeout,0 +620095,1,4120,success,0 +620096,1,4379,success,0 +620097,1,4125,success,0 +620098,0,4650,timeout,0 +620099,0,4650,timeout,0 diff --git a/policies/saucepan_to_hob/astra-s2/policy.py b/policies/saucepan_to_hob/astra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..51ed4f66125ba478a50dff981d3fd21c3a5a2dc3 --- /dev/null +++ b/policies/saucepan_to_hob/astra-s2/policy.py @@ -0,0 +1,83 @@ +"""Deterministic, hand-tuned saucepan manipulation controller. + +The motion stages open the cabinet, approach the handle, withdraw the pan, +raise it over the counter, and release it on the hob. Navigation uses measured +pelvis position and yaw. Arm waypoints are manually tuned physical targets; +there are no learned parameters, seed-specific branches, or external assets. +""" + +import numpy as np + +class Policy: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action()).copy() + # Close the walking loop in world coordinates, respecting the walk deadband. + def drive(self,a,obs,target): + p=obs["low_dim_obs"][21:25];err=np.asarray(target[:2])-p[:2];v=np.clip(err*2,-.18,.18) + if np.linalg.norm(err)<.012:v*=0 + elif np.linalg.norm(v)<.065:v*=.065/max(np.linalg.norm(v),1e-6) + c,s=np.cos(p[3]),np.sin(p[3]);a[:2]=[c*v[0]+s*v[1],-s*v[0]+c*v[1]];a[3]=np.clip((target[2]-p[3])*2,-.4,.4) + return a + def act(self,obs,tools): + t=obs['t'];a=self.a.copy();a[:5]=[0,0,.74,0,0];a[5:19]=0;a[19:]=0 + a[5]=.3;a[7]=.3;a[10]=-.3;a[11]=-.3;a[12]=.8 + # Reach the cabinet handle, close the left fingers, and pull the door open. + if t<90:a[0]=.1 + elif t<190:a[2]=.55 + elif t<340: + a[2]=.65 + if t<290:a[7]=.43;a[11]=-.43 + elif t<540: + a[2]=.65;a[19]=1 + if t>=380:a[5]=0;a[8]=.6;a[10]=-.6 + if t>=450:a[5]=-.3;a[8]=1.2;a[10]=-.9;a[7]=.2;a[11]=-.2 + elif t<830: + a[19]=1;a[5]=-.1;a[8]=1.2;a[10]=-1.1;a[7]=.2;a[11]=-.2;a[0]=-.12 + if t>=650:a[0]=-.16;a[1]=-.1 + elif t<1010: + a[19]=1;a[5]=-.1;a[8]=1.2;a[10]=-1.1;a[7]=.2;a[11]=-.2 + a=self.drive(a,obs,[0,-.6,.7]) + else: + # Walk around the free edge of the open door before approaching the shelf. + a[5:19]=0;a[5]=a[12]=.8 + if t<1080:pass + elif t<1460:a=self.drive(a,obs,[-.1,.45,0]) + elif t<1690:a=self.drive(a,obs,[.4,.3,0]) + elif t<1840:a=self.drive(a,obs,[.45,.08,0]);a[12]=.3;a[17]=-.3 + elif t<2070:a=self.drive(a,obs,[.5,0,0]);a[5]=.5;a[12]=.3;a[17]=.6 + else: + a[5]=.5 + # Each pose contains height, torso pitch, right shoulder pitch, elbow, + # wrist roll/pitch/yaw, and right gripper closure. Interpolation limits + # abrupt motions during contact, withdrawal, and placement. + points=[ + (2070, [.74,0,.3,0,0,.6,0,0]), + (2190, [.66,0,-.1,0,1.57,0,-1.4,0]), + (2290, [.66,.2,-.3,0,1.57,0,-1.4,.6]), + (2390, [.66,.4,-.5,0,1.57,0,-1.4,.6]), + (2490, [.66,.12,-.22,0,1.57,0,-1.4,0]), + (2590, [.6,.27,-.37,0,1.57,0,-1.4,.6]), + (2650, [.6,.23,-.33,0,1.57,0,-1.4,1]), + (2790, [.6,.23,-.93,1.2,1.57,0,-.8,1]), + (2930, [.74,.23,-.55,1.2,1.57,0,-.42,1]), + (3160, [.74,.23,-.55,1.2,1.57,0,-.42,1]), + (3320, [.78,.25,-1.6,.8,1.57,0,-1.55,1]), + (3560, [.78,.25,-1.6,.8,1.57,0,-1.55,1]), + (3680, [.79,.25,-1.6,.8,1.57,0,-1.55,1]), + (3760, [.79,.25,-1.6,.8,1.57,0,-.9,1]), + (3840, [.79,.25,-1.6,.8,1.57,0,-.3,1]), + (3990, [.74,.25,-1,.8,1.57,0,-1.25,1]), + ] + pose=np.asarray(points[-1][1],dtype=float) + for (t0,p0),(t1,p1) in zip(points,points[1:]): + if t=3990:a[20]=0 + if t>=4050: + u=min(1,(t-4050+1)/90);a[12]=-1-.5*u;a[18]=-1.25-.35*u + if t>=4140:a=self.drive(a,obs,[.25,.08,0]) + return a diff --git a/policies/saucepan_to_hob/astra-s3/episodes.csv b/policies/saucepan_to_hob/astra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..3c8755ee3108e43f3e2dc223508f90c2b8d44f42 --- /dev/null +++ b/policies/saucepan_to_hob/astra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,4565,success,0 +620001,0,4650,timeout,0 +620002,1,4524,success,0 +620003,1,4565,success,0 +620004,1,4552,success,0 +620005,0,4650,timeout,0 +620006,0,4650,timeout,0 +620007,0,4650,timeout,0 +620008,0,4650,timeout,0 +620009,1,4564,success,0 +620010,1,4586,success,0 +620011,1,4550,success,0 +620012,1,4533,success,0 +620013,0,4650,timeout,0 +620014,1,4550,success,0 +620015,0,4650,timeout,0 +620016,0,4650,timeout,0 +620017,0,4650,timeout,0 +620018,0,4650,timeout,0 +620019,1,4568,success,0 +620020,1,4552,success,0 +620021,1,4568,success,0 +620022,0,4650,timeout,0 +620023,1,4566,success,0 +620024,0,4650,timeout,0 +620025,0,4650,timeout,0 +620026,1,4565,success,0 +620027,0,4650,timeout,0 +620028,0,4650,timeout,0 +620029,0,4650,timeout,0 +620030,0,4650,timeout,0 +620031,1,4558,success,0 +620032,0,4650,timeout,0 +620033,0,4650,timeout,0 +620034,1,4567,success,0 +620035,1,4567,success,0 +620036,1,4566,success,0 +620037,1,4588,success,0 +620038,1,4564,success,0 +620039,0,4650,timeout,0 +620040,1,4552,success,0 +620041,0,4650,timeout,0 +620042,1,4589,success,0 +620043,0,4650,timeout,0 +620044,1,4571,success,0 +620045,0,4650,timeout,0 +620046,0,4650,timeout,0 +620047,1,4566,success,0 +620048,1,4524,success,0 +620049,0,4650,timeout,0 +620050,0,4650,timeout,0 +620051,0,4650,timeout,0 +620052,0,4650,timeout,0 +620053,1,4586,success,0 +620054,1,4549,success,0 +620055,1,4533,success,0 +620056,1,4568,success,0 +620057,1,4524,success,0 +620058,1,4566,success,0 +620059,0,4650,timeout,0 +620060,0,4650,timeout,0 +620061,0,4650,timeout,0 +620062,1,4524,success,0 +620063,1,4563,success,0 +620064,1,4550,success,0 +620065,0,4650,timeout,0 +620066,0,4650,timeout,0 +620067,0,4650,timeout,0 +620068,0,4650,timeout,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,1,4524,success,0 +620073,1,4551,success,0 +620074,0,4650,timeout,0 +620075,0,4650,timeout,0 +620076,0,4650,timeout,0 +620077,0,4650,timeout,0 +620078,0,4650,timeout,0 +620079,0,4650,timeout,0 +620080,0,4650,timeout,0 +620081,1,4550,success,0 +620082,1,4569,success,0 +620083,1,4524,success,0 +620084,0,4650,timeout,0 +620085,0,4650,timeout,0 +620086,1,4568,success,0 +620087,0,4650,timeout,0 +620088,0,4650,timeout,0 +620089,1,4566,success,0 +620090,1,4566,success,0 +620091,0,4650,timeout,0 +620092,1,4524,success,0 +620093,0,4650,timeout,0 +620094,1,4524,success,0 +620095,1,4568,success,0 +620096,0,4650,timeout,0 +620097,1,4567,success,0 +620098,1,4524,success,0 +620099,0,4650,timeout,0 diff --git a/policies/saucepan_to_hob/astra-s3/policy.py b/policies/saucepan_to_hob/astra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..655597a9950425060c01812238173ba3872c9d16 --- /dev/null +++ b/policies/saucepan_to_hob/astra-s3/policy.py @@ -0,0 +1,108 @@ +"""Deterministic camera-guided cabinet and saucepan manipulation. + +Uses a colour/shape detector for the cabinet handle, pelvis feedback for +walking, and a wrist-camera check to choose the saucepan grasp approach. +All motion targets are handwritten physical joint angles. +""" +import numpy as np +import cv2 + +def handle(im): + lo=im.min(2);hi=im.max(2) + mask=((hi-lo<12)&(lo>38)&(hi<125)).astype('uint8');mask[:,:8]=0;mask[:,76:]=0 + n,l,stats,cents=cv2.connectedComponentsWithStats(mask) + candidates=[] + for s,c in zip(stats[1:],cents[1:]): + x,y,w,h,area=s + if h>17 and w<32 and area>40 and h>w*1.5:candidates.append((abs(c[0]-42)+abs(c[1]-42)*.3,c,s)) + if not candidates:return None + _,c,s=min(candidates,key=lambda v:v[0]);return c,s + +class Policy: + def reset(self,obs,tools): + self.a=np.asarray(tools.hold_action()).copy(); self.stage=-1; self.checked=False; self.alternative=False + def move(self,obs,target): + pos=obs['low_dim_obs'][21:25];delta=np.array(target[:2])-pos[:2];v=np.clip(delta*2,-.15,.15);v[np.abs(delta)<.012]=0;norm=np.linalg.norm(v) + if 0=2580 and not self.checked: + im=tools.image('right_wrist').astype(np.float32) + r,g,b=im[:,:,0],im[:,:,1],im[:,:,2] + gold=(r>90)&(r>1.12*g)&(g>1.12*b)&(b<180) + self.alternative=np.count_nonzero(gold)<80 + self.checked=True + stages=[(130,{5:.8,12:.8,19:0,20:0},(.23,.12,0),False), + (210,{0:0,1:0,3:0,5:.15},None,False), + (310,{},None,True),(410,{4:.15,5:.04},None,True), + (510,{},(.33,.12,0),True),(590,{0:0,1:0,3:0},None,True), + (640,{19:1,7:.18,5:.06},None,False), + (720,{5:-.34,8:.8},None,False), + (810,{5:-.55,8:1.3,10:-.3,7:.1},None,False), + (1150,{},(-.4,-.5,0),False), + (1230,{19:0,5:2,6:.3,7:0,8:0,10:0,4:0,0:0,1:0,3:0,12:2,13:-.3,15:0},None,False), + (1530,{},(-.25,.08,0),False), + (1830,{},(.42,.08,0),False), + (1900,{0:0,1:0,3:0},None,False), + (2000,{12:0,13:0,14:.2,15:1.5,16:-1.57,18:-.7},None,False), + (2120,{2:.6},None,False), + (2220,{12:.1,15:.8,18:-.6},None,False), + (2320,{12:-.6,15:.8,18:0},None,False), + (2390,{16:0,17:-.4},None,False), + (2460,{17:.6},None,False), + (2530,{16:-1.57,17:0,18:.6},None,False), + (2580,{12:-.67},None,False), + (2640,{20:1},None,False), + (2730,{12:-.85,15:1.1,18:.45},None,False), + (2790,{2:.65,12:-.75,18:.35},None,False), + (2850,{2:.7,12:-.65,18:.25},None,False), + (2910,{2:.74,12:-.57,18:.17},None,False), + (3100,{},(.05,.08,0),False), + (3160,{0:0,1:0,3:0},None,False), + (3220,{12:-.77,18:.37},None,False), + (3280,{12:-.97,18:.57},None,False), + (3340,{12:-1.17,18:.77},None,False), + (3400,{12:-1.4,18:1},None,False), + (3460,{12:-1.65,18:1.25},None,False), + (3710,{},(.45,-.06,0),False), + (3780,{0:0,1:0,3:0},None,False), + (3880,{12:-1.95,18:1.55,2:.8},None,False), + (4080,{},(.4,-.06,0),False), + (4140,{0:0,1:0,3:0},None,False), + (4260,{},(.4,-.2,0),False), + (4340,{0:0,1:0,3:0,12:-1.85,18:1.45},None,False), + (4400,{13:-.25,16:-1.32},None,False), + (4460,{12:-1.72,18:1.32},None,False), + (4651,{20:0},None,False)] + if self.alternative: + stages=[s for s in stages if s[0]<=2580]+[ + (2640,{18:.9},None,False), + (2700,{14:.35,18:.6},None,False), + (2760,{14:.5},None,False), + (2830,{14:-.1},None,False), + (2900,{12:-.85,14:.2,15:1.1,18:.45},None,False), + (2980,{2:.55},None,False), + (3050,{12:-1.05,15:1.5,18:.25},None,False), + (3110,{20:1},None,False), + (3190,{2:.65,12:-.85,18:.05},None,False), + (3270,{2:.74,12:-.67,18:-.13},None,False), + (3450,{},(.05,.08,0),False), + (3530,{0:0,1:0,3:0,12:-.57,15:1.1,18:.17},None,False), + (3630,{12:-1.2,18:.8},None,False), + (3770,{12:-1.95,18:1.55,2:.8},None,False), + (4030,{},(.4,-.06,0),False), + (4110,{0:0,1:0,3:0,13:-.25,16:-1.32},None,False), + (4210,{12:-1.72,18:1.32},None,False), + (4651,{20:0},None,False)] + for i,(end,changes,target,servo) in enumerate(stages): + if t= 4) & (H <= 28) & (S >= 70) & (S <= 235) + & (V >= 55) & (V <= 200)).astype(np.uint8) + # ignore the top strip (wooden counter) and the very bottom edge + mask[:max(6, h // 6), :] = 0 + mask[int(h * 0.94):, :] = 0 + n, lab, stats, cent = cv2.connectedComponentsWithStats(mask, 8) + best = (0, w / 2.0, h / 2.0) + for i in range(1, n): + area = int(stats[i, 4]) + if area > best[0]: + best = (area, float(cent[i, 0]), float(cent[i, 1])) + return best + except Exception: + return (0, 0.0, 0.0) + + def _check_pan(self): + """Look for the saucepan in the head and right-wrist cameras.""" + try: + head = self.tools.image("head", 84, 84) + wrist = self.tools.image("right_wrist", 84, 84) + except Exception: + return False + ah, cxh, cyh = self._brown_blob(head) + aw, cxw, cyw = self._brown_blob(wrist) + # The pan is a compact brown blob (a few hundred pixels at most). + hit = False + if 20 <= ah <= 520 and 0.25 * 84 < cxh < 0.90 * 84 and cyh > 33: + hit = True + if 18 <= aw <= 520 and 0.20 * 84 < cxw < 0.90 * 84 and cyw > 30: + hit = True + self.pan_hits = self.pan_hits + 1 if hit else 0 + return self.pan_hits >= 3 + + # ------------------------------------------------------------------ + # scripted door-opening repertoire + # ------------------------------------------------------------------ + def _set_seg(self, target, n): + self.seg = np.asarray(target, dtype=np.float32).copy() + self.seg_len = int(n) + self.seg_k = 0 + + def _run_seg(self, obs): + """Return the action of the current scripted segment, or None if done.""" + if self.seg is None or self.seg_k >= self.seg_len: + return None + a = self.seg.copy() + self.seg_k += 1 + return a + + def _opening_script(self, obs, t): + """Main door-opening state machine. Returns an action.""" + lo = self._pose(obs) + x = float(lo[21]) + # The hold target keeps all joints at their current values. + h = self.hold.copy() + + # ---- phase 0: stand close to the cabinet with arms retracted + if self.phase == 0: + a = h.copy() + a[0] = 0.5 + a[2] = 0.72 + a[4] = 0.55 + a[5] = -0.5 + a[8] = 1.5 + a[12] = -0.5 + a[15] = 1.5 + if x > 0.40 or self.phase_t > 150: + self.phase = 1 + self.phase_t = 0 + return self._apply_limits(a) + + # ---- phase 1: place both hands on the drawer/door top edge + if self.phase == 1: + a = h.copy() + a[0] = 0.05 + a[2] = 0.68 + a[4] = 0.25 if self.phase_t > 20 else 0.0 + a[5] = 0.30 + a[8] = 0.10 + a[12] = 0.30 + a[15] = 0.10 + if self.phase_t > 45: + self.phase = 2 + self.phase_t = 0 + return self._apply_limits(a) + + # ---- phase 2: close and pull the panel down / towards the robot + if self.phase == 2: + u = min(1.0, self.phase_t / 50.0) + a = h.copy() + a[0] = 0.10 * (1.0 - u) - 0.45 * u + a[2] = 0.68 - 0.20 * u + a[4] = 0.0 + 0.35 * u + a[5] = 0.30 - 0.75 * u + a[8] = 0.10 + 0.55 * u + a[12] = 0.30 - 0.75 * u + a[15] = 0.10 + 0.55 * u + a[19] = 1.0 + a[20] = 1.0 + if self.phase_t > 70: + self.phase = 3 + self.phase_t = 0 + return self._apply_limits(a) + + # ---- phase 3: alternate hook/push/pull attempts then random search + u = self.phase_t + # A small deterministic repertoire, then a seeded random exploration. + if u < 40: + a = h.copy() + a[0] = -0.35 + a[5] = -0.30 + 0.03 * u + a[12] = -0.30 + 0.03 * u + a[19] = 0.0 + a[20] = 0.0 + return self._apply_limits(a) + if u < 80: + a = h.copy() + a[0] = 0.10 + a[2] = 0.55 + a[4] = 0.60 + a[5] = 0.45 + a[8] = 0.40 + a[12] = 0.45 + a[15] = 0.40 + a[19] = 0.0 + a[20] = 0.0 + return self._apply_limits(a) + if u < 120: + a = h.copy() + a[0] = -0.25 + a[2] = 0.45 + a[5] = 0.55 + a[8] = 1.2 + a[12] = 0.55 + a[15] = 1.2 + a[19] = 1.0 + a[20] = 1.0 + return self._apply_limits(a) + if u < 160: + a = h.copy() + a[0] = 0.0 + a[1] = 0.35 + a[5] = -0.2 + a[8] = 0.2 + a[12] = -0.2 + a[15] = 0.2 + a[19] = 1.0 + a[20] = 1.0 + return self._apply_limits(a) + + # structured randomized exploration (deterministic; seeded RNG): + # alternate a random reach with a strong pull from the reached pose. + if self.seg is None or self.seg_k >= self.seg_len: + rng = self.rng + if self.last_mode == 'reach' and rng.random() < 0.75: + # pull segment: keep the reach pose, close and pull back/down + a = h.copy() + a[0] = -0.40 + a[1] = 0.0 + a[3] = 0.0 + a[2] = float(rng.choice([0.65, 0.70, 0.74])) + a[4] = float(rng.choice([0.0, 0.2, 0.4])) + a[5] = float(h[5]) - 0.35 + a[8] = float(h[8]) + 0.25 + a[12] = float(h[12]) - 0.35 + a[15] = float(h[15]) + 0.25 + a[19] = 1.0 + a[20] = 1.0 + self.last_mode = 'pull' + self._set_seg(a, int(rng.integers(10, 18))) + else: + a = h.copy() + a[0] = float(rng.choice([-0.20, -0.1, 0.0, 0.1, 0.20])) + a[1] = float(rng.choice([-0.20, 0.0, 0.0, 0.20])) + a[3] = float(rng.choice([-0.25, 0.0, 0.0, 0.25])) + a[2] = float(rng.choice([0.60, 0.65, 0.70, 0.74])) + a[4] = float(rng.choice([-0.2, 0.0, 0.2, 0.5, 0.8])) + sp = float(rng.uniform(-0.3, 0.7)) + el = float(rng.uniform(-0.5, 1.4)) + wp = float(rng.uniform(-1.0, 1.0)) + wr = float(rng.uniform(-1.5, 1.5)) + a[5] = sp + a[8] = el + a[10] = wp + a[9] = wr + a[12] = sp + float(rng.uniform(-0.3, 0.3)) + a[15] = el + float(rng.uniform(-0.3, 0.3)) + a[17] = wp + float(rng.uniform(-0.4, 0.4)) + a[16] = -wr + a[19] = float(rng.choice([0.0, 0.0, 0.5, 1.0])) + a[20] = float(rng.choice([0.0, 0.0, 0.5, 1.0])) + # keep the robot anchored in front of the cabinet and facing it + x = float(lo[21]); y = float(lo[22]); yaw = float(lo[24]) + if x < 0.20: + a[0] = 0.25 + elif x > 0.42: + a[0] = -0.25 + if abs(y) > 0.22: + a[1] = -0.25 * np.sign(y) + if abs(yaw) > 0.35: + a[3] = -0.30 * np.sign(yaw) + self.last_mode = 'reach' + self._set_seg(a, int(rng.integers(12, 25))) + return self._apply_limits(self._run_seg(obs)) + + # ------------------------------------------------------------------ + # visual-servo grasp / lift + # ------------------------------------------------------------------ + def _grasp(self, obs): + h = self.hold.copy() + lo = self._pose(obs) + try: + wrist = self.tools.image("right_wrist", 84, 84) + except Exception: + wrist = None + if wrist is None: + return self._apply_limits(h) + area, cx, cy = self._brown_blob(wrist) + ex = (cx - 42.0) / 42.0 + ey = (cy - 42.0) / 42.0 + # keep the previous joint targets, correct towards the blob + a = h.copy() + base_sp = float(lo[12]) + base_el = float(lo[15]) + base_roll = float(lo[13]) + base_yaw = float(lo[14]) + a[12] = base_sp - 0.20 * ey + a[15] = base_el + 0.05 + a[13] = base_roll - 0.20 * ex + a[14] = base_yaw + a[0] = 0.06 + a[19] = 0.0 + a[20] = 0.0 + self.grasp_t += 1 + if area >= 18 and abs(ex) < 0.35 and abs(ey) < 0.5: + a[20] = 1.0 + self.grasp_t += 2 + if self.grasp_t > 25: + # close and lift + a[20] = 1.0 + a[12] = base_sp + 0.6 + a[15] = base_el + 0.4 + a[0] = -0.15 + if self.grasp_t > 70: + # carry over the hob and release + a[12] = 0.65 + a[15] = 0.25 + a[17] = 0.7 + a[13] = 0.0 + a[0] = 0.0 + a[20] = 0.0 + a[19] = 0.0 + return self._apply_limits(a) + + # ------------------------------------------------------------------ + # main entry point + # ------------------------------------------------------------------ + def act(self, obs, tools): + self.tools = tools + t = int(obs.get("t", 0)) + if t <= self.last_t: + # a new episode began without reset + self.reset(obs, tools) + self.phase_t += 1 + self.last_t = t + # keep an up-to-date hold target + try: + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + except Exception: + pass + + if self.phase >= 10: + return self._grasp(obs) + + # periodically look for the pan; if it appears, go for it + if (t % 7) == 0: + if self._check_pan(): + self.phase = 10 + self.grasp_t = 0 + return self._grasp(obs) + + a = self._opening_script(obs, t) + if a is None: + a = self.hold.copy() + return self._apply_limits(a) diff --git a/policies/saucepan_to_hob/deepseek1017-s2/episodes.csv b/policies/saucepan_to_hob/deepseek1017-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8bdd4e6043da73ac776c1ce5081f089e7a50e206 --- /dev/null +++ b/policies/saucepan_to_hob/deepseek1017-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4650,timeout,0 +620001,0,4650,timeout,0 +620002,0,4650,timeout,0 +620003,0,4650,timeout,0 +620004,0,4650,timeout,0 +620005,0,4650,timeout,0 +620006,0,4650,timeout,0 +620007,0,4650,timeout,0 +620008,0,4650,timeout,0 +620009,0,4650,timeout,0 +620010,0,4650,timeout,0 +620011,0,4650,timeout,0 +620012,0,4650,timeout,0 +620013,0,4650,timeout,0 +620014,0,4650,timeout,0 +620015,0,4650,timeout,0 +620016,0,4650,timeout,0 +620017,0,4650,timeout,0 +620018,0,4650,timeout,0 +620019,0,4650,timeout,0 +620020,0,4650,timeout,0 +620021,0,4650,timeout,0 +620022,0,4650,timeout,0 +620023,0,4650,timeout,0 +620024,0,4650,timeout,0 +620025,0,4650,timeout,0 +620026,0,4650,timeout,0 +620027,0,4650,timeout,0 +620028,0,4650,timeout,0 +620029,0,4650,timeout,0 +620030,0,4650,timeout,0 +620031,0,4650,timeout,0 +620032,0,4650,timeout,0 +620033,0,4650,timeout,0 +620034,0,4650,timeout,0 +620035,0,4650,timeout,0 +620036,0,4650,timeout,0 +620037,0,4650,timeout,0 +620038,0,4650,timeout,0 +620039,0,4650,timeout,0 +620040,0,4650,timeout,0 +620041,0,4650,timeout,0 +620042,0,4650,timeout,0 +620043,0,4650,timeout,0 +620044,0,4650,timeout,0 +620045,0,4650,timeout,0 +620046,0,4650,timeout,0 +620047,0,4650,timeout,0 +620048,0,4650,timeout,0 +620049,0,4650,timeout,0 +620050,0,4650,timeout,0 +620051,0,4650,timeout,0 +620052,0,4650,timeout,0 +620053,0,4650,timeout,0 +620054,0,4650,timeout,0 +620055,0,4650,timeout,0 +620056,0,4650,timeout,0 +620057,0,4650,timeout,0 +620058,0,4650,timeout,0 +620059,0,4650,timeout,0 +620060,0,4650,timeout,0 +620061,0,4650,timeout,0 +620062,0,4650,timeout,0 +620063,0,4650,timeout,0 +620064,0,4650,timeout,0 +620065,0,4650,timeout,0 +620066,0,4650,timeout,0 +620067,0,4650,timeout,0 +620068,0,4650,timeout,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,0,4650,timeout,0 +620073,0,4650,timeout,0 +620074,0,4650,timeout,0 +620075,0,4650,timeout,0 +620076,0,4650,timeout,0 +620077,0,4650,timeout,0 +620078,0,4650,timeout,0 +620079,0,4650,timeout,0 +620080,0,4650,timeout,0 +620081,0,4650,timeout,0 +620082,0,4650,timeout,0 +620083,0,4650,timeout,0 +620084,0,4650,timeout,0 +620085,0,4650,timeout,0 +620086,0,4650,timeout,0 +620087,0,4650,timeout,0 +620088,0,4650,timeout,0 +620089,0,4650,timeout,0 +620090,0,4650,timeout,0 +620091,0,4650,timeout,0 +620092,0,4650,timeout,0 +620093,0,4650,timeout,0 +620094,0,4650,timeout,0 +620095,0,4650,timeout,0 +620096,0,4650,timeout,0 +620097,0,4650,timeout,0 +620098,0,4650,timeout,0 +620099,0,4650,timeout,0 diff --git a/policies/saucepan_to_hob/deepseek1017-s2/policy.py b/policies/saucepan_to_hob/deepseek1017-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..b8e03407025cd653acef327b3064f1f3bf24a051 --- /dev/null +++ b/policies/saucepan_to_hob/deepseek1017-s2/policy.py @@ -0,0 +1,292 @@ +"""Hand-written control policy for the saucepan_to_hob task. + +The robot starts right in front of a cupboard whose front panel hides a +saucepan. Only the robot's own cameras and body state are available, so the +controller is a deterministic, time-based sequence of joint targets with a +small amount of camera-driven adaptation (a colour detector for the copper +pan). Everything is in physical units and one ``act`` call is 0.02 s. +""" + +import numpy as np +import cv2 + + +def _blend(a, b, f): + """Linear interpolation between two action vectors.""" + return a * (1.0 - f) + b * f + + +class Policy: + """Deterministic scripted controller.""" + + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + # the grippers start almost shut; keep them fully open while reaching + self.base = self.hold.copy() + self.base[19] = 0.0 + self.base[20] = 0.0 + self.t = 0 + self.pan_seen = False + self.pan_time = 0 + self.best_cu = 0.0 + self.hits = 0 + + # -- action construction ------------------------------------------------ + def pose(self, **kw): + a = self.base.copy() + idx = { + "vx": 0, "vy": 1, "h": 2, "wz": 3, "pitch": 4, + "lsp": 5, "lsr": 6, "lsy": 7, "le": 8, + "lwr": 9, "lwp": 10, "lwy": 11, "lg": 19, + "rsp": 12, "rsr": 13, "rsy": 14, "re": 15, + "wr": 16, "wp": 17, "wy": 18, "g": 20, + } + for k, v in kw.items(): + a[idx[k]] = v + return a + + # -- vision ------------------------------------------------------------- + @staticmethod + def pan_score(im, region=True): + """Largest compact copper blob (the saucepan), as a pixel fraction.""" + f = im.astype(np.float32) + R, G, B = f[..., 0], f[..., 1], f[..., 2] + m = ((R > 75) & (R - G > 18) & (G - B > 5) & + (R > G * 1.12) & (R - B > 35)).astype(np.uint8) + if region: + m[:14, :] = 0 + m[:, :8] = 0 + m[:, 76:] = 0 + n, lab, stats, cents = cv2.connectedComponentsWithStats(m, 8) + best = 0.0 + for i in range(1, n): + area = int(stats[i, cv2.CC_STAT_AREA]) + if area < 25 or area > 900: + continue + w = int(stats[i, cv2.CC_STAT_WIDTH]) + h = int(stats[i, cv2.CC_STAT_HEIGHT]) + if w > 48 or h > 48: + continue + if cents[i][1] < 16: + continue + if area / float(w * h) < 0.35: + continue + best = max(best, area / float(im.shape[0] * im.shape[1])) + if best > 0.0: + break + return best + + # -- main loop ---------------------------------------------------------- + def act(self, obs, tools): + self.t += 1 + t = self.t + + # look for the pan (rendering costs no budget) + if t % 6 == 0: + try: + hs = self.pan_score(tools.image("head"), region=True) + ws = 0.0 + if hs < 0.018: + ws = self.pan_score(tools.image("right_wrist"), + region=False) + cu = max(hs, ws) + if cu > self.best_cu: + self.best_cu = cu + ok = (t > 1550) and ((hs > 0.020) or (ws > 0.030)) + self.hits = (self.hits + 1) if ok else 0 + if self.hits >= 2 and not self.pan_seen: + self.pan_seen = True + self.pan_time = t + except Exception: + pass + + if obs.get("fell", False): + return self.pose() + + if self.pan_seen: + return self.act_pan(t - self.pan_time) + + return self.act_open(t) + + # ------------------------------------------------------------------ + # stage 1: try to open the cupboard + # ------------------------------------------------------------------ + def act_open(self, t): + # A. two hands on the top edge, open grippers, close, pull down + if t < 30: + return self.pose() + if t < 95: + f = min(1.0, (t - 30) / 60.0) + a = self.pose(h=0.74, pitch=0.0) + b = self.pose(h=0.90, rsp=-0.50, re=0.95, + lsp=-0.50, le=0.95, g=0.0, lg=0.0) + return _blend(a, b, f) + if t < 120: + return self.pose(h=0.90, rsp=-0.50, re=0.95, + lsp=-0.50, le=0.95, g=1.0, lg=1.0) + if t < 250: + f = min(1.0, (t - 120) / 110.0) + a = self.pose(h=0.90, rsp=-0.50, re=0.95, + lsp=-0.50, le=0.95, g=1.0, lg=1.0) + b = self.pose(h=0.46, rsp=0.30, re=0.25, pitch=0.20, + lsp=0.30, le=0.25, g=1.0, lg=1.0, vx=-0.20) + return _blend(a, b, f) + if t < 290: + return self.pose(h=0.70, g=0.0, lg=0.0) + + # B. step to the right, grab the top edge there, pull down + if t < 340: + return self.pose(h=0.80, vy=-0.30, g=0.0, lg=0.0) + if t < 400: + f = min(1.0, (t - 340) / 50.0) + a = self.pose(h=0.80, g=0.0, lg=0.0) + b = self.pose(h=0.90, rsp=-0.50, re=0.95, + lsp=-0.50, le=0.95, g=0.0, lg=0.0) + return _blend(a, b, f) + if t < 425: + return self.pose(h=0.90, rsp=-0.50, re=0.95, + lsp=-0.50, le=0.95, g=1.0, lg=1.0) + if t < 540: + f = min(1.0, (t - 425) / 100.0) + a = self.pose(h=0.90, rsp=-0.50, re=0.95, + lsp=-0.50, le=0.95, g=1.0, lg=1.0) + b = self.pose(h=0.46, rsp=0.30, re=0.25, pitch=0.20, + lsp=0.30, le=0.25, g=1.0, lg=1.0, vx=-0.20) + return _blend(a, b, f) + if t < 580: + return self.pose(h=0.74, g=0.0, lg=0.0) + + # C. turn left and use the right hand on the panel edge + if t < 660: + return self.pose(wz=0.3, g=0.0, lg=0.0) + if t < 710: + f = min(1.0, (t - 660) / 45.0) + a = self.pose() + b = self.pose(h=0.86, rsp=-0.55, re=0.95, g=0.0) + return _blend(a, b, f) + if t < 730: + return self.pose(h=0.86, rsp=-0.55, re=0.95, g=1.0) + if t < 840: + f = min(1.0, (t - 730) / 100.0) + a = self.pose(h=0.86, rsp=-0.55, re=0.95, g=1.0) + b = self.pose(h=0.45, rsp=0.35, re=0.20, g=1.0, vx=-0.20) + return _blend(a, b, f) + if t < 880: + return self.pose(h=0.74, g=0.0) + + # D. squat, push both hands up under the panel, then stand and lift + if t < 940: + f = min(1.0, (t - 880) / 55.0) + a = self.pose(h=0.74) + b = self.pose(h=0.45, rsp=-0.55, re=0.45, + lsp=-0.55, le=0.45, g=0.0, lg=0.0) + return _blend(a, b, f) + if t < 960: + return self.pose(h=0.45, rsp=-0.55, re=0.45, + lsp=-0.55, le=0.45, g=1.0, lg=1.0) + if t < 1060: + f = min(1.0, (t - 960) / 95.0) + a = self.pose(h=0.45, rsp=-0.55, re=0.45, + lsp=-0.55, le=0.45, g=1.0, lg=1.0) + b = self.pose(h=0.95, rsp=-0.95, re=0.15, pitch=0.15, + lsp=-0.95, le=0.15, g=1.0, lg=1.0) + return _blend(a, b, f) + if t < 1100: + return self.pose(h=0.74, g=0.0, lg=0.0) + + # E. another slow two-hand drag with fully open grippers + if t < 1140: + return self.pose(h=0.90, rsp=-0.50, re=0.95, + lsp=-0.50, le=0.95, g=0.0, lg=0.0) + if t < 1160: + return self.pose(h=0.90, rsp=-0.50, re=0.95, + lsp=-0.50, le=0.95, g=1.0, lg=1.0) + if t < 1320: + f = min(1.0, (t - 1160) / 155.0) + a = self.pose(h=0.90, rsp=-0.50, re=0.95, + lsp=-0.50, le=0.95, g=1.0, lg=1.0) + b = self.pose(h=0.44, rsp=0.30, re=0.20, pitch=0.35, + lsp=0.30, le=0.20, g=1.0, lg=1.0, vx=-0.25) + return _blend(a, b, f) + + # F. repeat the grab attempt (the door may give way) + if t < 1360: + return self.pose(h=0.72, g=0.0, lg=0.0) + if t < 1420: + return self.pose(h=0.90, rsp=-0.50, re=0.95, + lsp=-0.50, le=0.95, g=0.0, lg=0.0) + if t < 1440: + return self.pose(h=0.90, rsp=-0.50, re=0.95, + lsp=-0.50, le=0.95, g=1.0, lg=1.0) + if t < 1600: + f = min(1.0, (t - 1440) / 155.0) + a = self.pose(h=0.90, rsp=-0.50, re=0.95, + lsp=-0.50, le=0.95, g=1.0, lg=1.0) + b = self.pose(h=0.44, rsp=0.30, re=0.20, pitch=0.35, + lsp=0.30, le=0.20, g=1.0, lg=1.0, vx=-0.25) + return _blend(a, b, f) + + # G. blind reach into the cupboard and sweep for the pan + return self.act_search((t - 1600) % 600) + + # ------------------------------------------------------------------ + # stage 2: reach into the cupboard / pick the pan + # ------------------------------------------------------------------ + def act_search(self, s): + if s < 60: + f = min(1.0, s / 55.0) + a = self.pose(h=0.70) + b = self.pose(h=0.52, rsp=-0.65, re=0.60, + lsp=-0.65, le=0.60, g=0.0, lg=0.0) + return _blend(a, b, f) + if s < 240: + f = (s - 60) / 180.0 + y = 0.9 * np.sin(2.0 * np.pi * f) + return self.pose(h=0.52, rsp=-0.65, re=0.60, + lsp=-0.65, le=0.60, rsy=y, lsy=-y, + g=0.0, lg=0.0) + if s < 270: + return self.pose(h=0.52, rsp=-0.65, re=0.60, + lsp=-0.65, le=0.60, g=1.0, lg=1.0) + if s < 380: + f = min(1.0, (s - 270) / 100.0) + a = self.pose(h=0.52, rsp=-0.65, re=0.60, + lsp=-0.65, le=0.60, g=1.0, lg=1.0) + b = self.pose(h=0.95, rsp=-0.95, re=0.10, pitch=0.20, + lsp=-0.95, le=0.10, g=1.0, lg=1.0) + return _blend(a, b, f) + if s < 470: + f = min(1.0, (s - 380) / 85.0) + a = self.pose(h=0.95, rsp=-0.95, re=0.10, pitch=0.20, + lsp=-0.95, le=0.10, g=1.0, lg=1.0) + b = self.pose(h=0.85, rsp=-0.60, re=0.55, pitch=0.55, + lsp=-0.60, le=0.55, g=1.0, lg=1.0) + return _blend(a, b, f) + if s < 530: + return self.pose(h=0.85, rsp=-0.60, re=0.55, pitch=0.55, + lsp=-0.60, le=0.55, g=0.0, lg=0.0) + return self.pose(h=0.74, g=0.0, lg=0.0) + + # ------------------------------------------------------------------ + # stage 3: pan has been seen -> grasp it and put it on the hob + # ------------------------------------------------------------------ + def act_pan(self, s): + if s < 40: + return self.pose(h=0.75, g=1.0, lg=1.0) + if s < 130: + f = min(1.0, (s - 40) / 85.0) + a = self.pose(h=0.75, g=1.0, lg=1.0) + b = self.pose(h=0.95, rsp=-0.95, re=0.10, pitch=0.20, + lsp=-0.95, le=0.10, g=1.0, lg=1.0) + return _blend(a, b, f) + if s < 220: + f = min(1.0, (s - 130) / 85.0) + a = self.pose(h=0.95, rsp=-0.95, re=0.10, pitch=0.20, + lsp=-0.95, le=0.10, g=1.0, lg=1.0) + b = self.pose(h=0.85, rsp=-0.60, re=0.55, pitch=0.55, + lsp=-0.60, le=0.55, g=1.0, lg=1.0) + return _blend(a, b, f) + if s < 280: + return self.pose(h=0.85, rsp=-0.60, re=0.55, pitch=0.55, + lsp=-0.60, le=0.55, g=0.0, lg=0.0) + return self.pose(h=0.74, g=0.0, lg=0.0) diff --git a/policies/saucepan_to_hob/deepseek1017-s3/episodes.csv b/policies/saucepan_to_hob/deepseek1017-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8bdd4e6043da73ac776c1ce5081f089e7a50e206 --- /dev/null +++ b/policies/saucepan_to_hob/deepseek1017-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4650,timeout,0 +620001,0,4650,timeout,0 +620002,0,4650,timeout,0 +620003,0,4650,timeout,0 +620004,0,4650,timeout,0 +620005,0,4650,timeout,0 +620006,0,4650,timeout,0 +620007,0,4650,timeout,0 +620008,0,4650,timeout,0 +620009,0,4650,timeout,0 +620010,0,4650,timeout,0 +620011,0,4650,timeout,0 +620012,0,4650,timeout,0 +620013,0,4650,timeout,0 +620014,0,4650,timeout,0 +620015,0,4650,timeout,0 +620016,0,4650,timeout,0 +620017,0,4650,timeout,0 +620018,0,4650,timeout,0 +620019,0,4650,timeout,0 +620020,0,4650,timeout,0 +620021,0,4650,timeout,0 +620022,0,4650,timeout,0 +620023,0,4650,timeout,0 +620024,0,4650,timeout,0 +620025,0,4650,timeout,0 +620026,0,4650,timeout,0 +620027,0,4650,timeout,0 +620028,0,4650,timeout,0 +620029,0,4650,timeout,0 +620030,0,4650,timeout,0 +620031,0,4650,timeout,0 +620032,0,4650,timeout,0 +620033,0,4650,timeout,0 +620034,0,4650,timeout,0 +620035,0,4650,timeout,0 +620036,0,4650,timeout,0 +620037,0,4650,timeout,0 +620038,0,4650,timeout,0 +620039,0,4650,timeout,0 +620040,0,4650,timeout,0 +620041,0,4650,timeout,0 +620042,0,4650,timeout,0 +620043,0,4650,timeout,0 +620044,0,4650,timeout,0 +620045,0,4650,timeout,0 +620046,0,4650,timeout,0 +620047,0,4650,timeout,0 +620048,0,4650,timeout,0 +620049,0,4650,timeout,0 +620050,0,4650,timeout,0 +620051,0,4650,timeout,0 +620052,0,4650,timeout,0 +620053,0,4650,timeout,0 +620054,0,4650,timeout,0 +620055,0,4650,timeout,0 +620056,0,4650,timeout,0 +620057,0,4650,timeout,0 +620058,0,4650,timeout,0 +620059,0,4650,timeout,0 +620060,0,4650,timeout,0 +620061,0,4650,timeout,0 +620062,0,4650,timeout,0 +620063,0,4650,timeout,0 +620064,0,4650,timeout,0 +620065,0,4650,timeout,0 +620066,0,4650,timeout,0 +620067,0,4650,timeout,0 +620068,0,4650,timeout,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,0,4650,timeout,0 +620073,0,4650,timeout,0 +620074,0,4650,timeout,0 +620075,0,4650,timeout,0 +620076,0,4650,timeout,0 +620077,0,4650,timeout,0 +620078,0,4650,timeout,0 +620079,0,4650,timeout,0 +620080,0,4650,timeout,0 +620081,0,4650,timeout,0 +620082,0,4650,timeout,0 +620083,0,4650,timeout,0 +620084,0,4650,timeout,0 +620085,0,4650,timeout,0 +620086,0,4650,timeout,0 +620087,0,4650,timeout,0 +620088,0,4650,timeout,0 +620089,0,4650,timeout,0 +620090,0,4650,timeout,0 +620091,0,4650,timeout,0 +620092,0,4650,timeout,0 +620093,0,4650,timeout,0 +620094,0,4650,timeout,0 +620095,0,4650,timeout,0 +620096,0,4650,timeout,0 +620097,0,4650,timeout,0 +620098,0,4650,timeout,0 +620099,0,4650,timeout,0 diff --git a/policies/saucepan_to_hob/deepseek1017-s3/policy.py b/policies/saucepan_to_hob/deepseek1017-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..bb0e1e33e1308e3ae4f3be3f39abe5fae19df754 --- /dev/null +++ b/policies/saucepan_to_hob/deepseek1017-s3/policy.py @@ -0,0 +1,299 @@ +"""Hand-written control policy for the saucepan-to-hob task. + +The robot starts facing a white floor-standing cabinet whose top is the black +glass hob. The saucepan is inside the cabinet behind the front door. The +policy is a deterministic state machine: + + 1. drive up to the cabinet with the arms tucked, + 2. make a repertoire of door-opening pulls (two-hand top edge, one-hand side, + low hook lift, closed-finger hook sweep), + 3. squat and sweep both wrist cameras through the opening while looking for + the copper pan and servo the right hand onto it, + 4. lift the pan and set it on the hob. + +All control is scripted; the cameras are used only for the copper detector and +for the door lip / handle alignment. There is no randomness and no wall-clock +dependence. +""" + +import numpy as np + +# --------------------------------------------------------------------------- +# helpers + + +def _clip_action(a): + a = np.asarray(a, dtype=np.float32).copy() + a[0] = np.clip(a[0], -1.0, 1.0) + a[1] = np.clip(a[1], -1.0, 1.0) + a[2] = np.clip(a[2], 0.40, 1.0) + a[3] = np.clip(a[3], -1.0, 1.0) + a[4] = np.clip(a[4], -0.20, 0.80) + a[5:19] = np.clip(a[5:19], -3.1, 3.1) + a[19:21] = np.clip(a[19:21], 0.0, 1.0) + return a + + +def _copper_stats(im): + """Copper-coloured pixels: (count, mean_x, mean_y).""" + if im is None: + return 0, -1.0, -1.0 + x = im.astype(np.float32) + r, g, b = x[:, :, 0], x[:, :, 1], x[:, :, 2] + m = ( + (r > 80) + & (r < 215) + & (g < 155) + & (b < 125) + & (r - g > 30) + & (r - b > 50) + ) + ys, xs = np.nonzero(m) + if len(ys) == 0: + return 0, -1.0, -1.0 + return int(len(ys)), float(xs.mean()), float(ys.mean()) + + +def _wood_stats(im): + """Bright wooden lip pixels: (count, mean_x, mean_y).""" + if im is None: + return 0, -1.0, -1.0 + x = im.astype(np.float32) + r, g, b = x[:, :, 0], x[:, :, 1], x[:, :, 2] + m = ( + (r > 120) + & (r < 245) + & (g > 100) + & (b < 170) + & (r - b > 40) + & (r > g + 5) + ) + ys, xs = np.nonzero(m) + if len(ys) == 0: + return 0, -1.0, -1.0 + return int(len(ys)), float(xs.mean()), float(ys.mean()) + + +class Policy: + """Deterministic hand-written controller.""" + + STAND_H = 0.745 + FACE_PITCH = 0.15 + SQUAT_H = 0.62 + + # ------------------------------------------------------------------ + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.target = self.hold.copy() + self.target[2] = self.STAND_H + self.target[4] = self.FACE_PITCH + self.t = 0 + self.phase = 0 + self.phase_t = 0 + self.open_round = 0 + self.pan_grab = False + self.pan_seen = 0 + self.copper = None + + # ------------------------------------------------------------------ + def _set_arms(self, left, right): + self.target[5:12] = left + self.target[12:19] = right + + def _set_left(self, left): + self.target[5:12] = left + + def _set_right(self, right): + self.target[12:19] = right + + def _set_grip(self, g): + self.target[19] = g + self.target[20] = g + + def _advance(self, phase): + self.phase = phase + self.phase_t = 0 + + def _find_pan(self, tools, full=False): + """Check the wrist camera (and head/left on ``full``) for copper.""" + best = (0, -1.0, -1.0) + cams = ("right_wrist",) if not full else ("right_wrist", "head", "left_wrist") + for cam in cams: + im = tools.image(cam, 84, 84) + c, cx, cy = _copper_stats(im) + if c > best[0]: + best = (c, cx, cy) + if c > 45: + if cam != "right_wrist": + # remap the centroid to the frame used by the servo + best = (c, -1.0, -1.0) + self.pan_seen += 1 + return best + return best + + # ------------------------------------------------------------------ + def _walk_to_cabinet(self): + self.target[0] = 0.22 + self.target[1] = 0.0 + self.target[3] = 0.0 + self.target[2] = self.STAND_H + self.target[4] = 0.05 + if self.phase_t > 105: + self.target[0] = 0.0 + self._advance(1) + + def _opening(self, tools): + """Repertoire of door-opening motions; checks the cameras for the pan.""" + n = 150 + seg = min(3, self.phase_t // n) + f = (self.phase_t % n) / float(n) + self.target[0] = 0.0 + self.target[1] = 0.0 + self.target[3] = 0.0 + self.target[2] = self.STAND_H + self.target[4] = self.FACE_PITCH + g = 1.0 + + if seg == 0: + # two hands on the top edge, pull down and out while retreating + sp = -0.80 + 0.55 * f + el = 0.15 + 0.35 * f + wp = 0.25 * (1.0 - f) + self._set_arms( + [sp, 0.12, 0.0, el, 0.0, wp, 0.0], + [sp, -0.12, 0.0, el, 0.0, wp, 0.0], + ) + self.target[4] = self.FACE_PITCH - 0.25 * f + self.target[0] = -0.16 * f + elif seg == 1: + # right hand at the side of the front, pull sideways / back + sp = -0.55 + 0.20 * f + el = 0.10 + 0.25 * f + self._set_right( + [sp, 0.30 * (0.3 + 0.7 * f), 0.0, el, 0.0, 0.30, -0.8 * f] + ) + self._set_left([-0.55, 0.10, 0.0, 0.20, 0.0, 0.30, 0.0]) + self.target[1] = -0.15 * f + elif seg == 2: + # low hook and lift (top-hinged variant) + sp = -0.20 - 0.65 * f + el = 0.10 + 0.25 * f + self._set_right( + [sp, -0.10, 0.0, el, 0.0, 0.30 * (1 - 0.5 * f), 0.0] + ) + self._set_left( + [-0.45, 0.10, 0.0, 0.20, 0.0, 0.30 * (1 - 0.5 * f), 0.0] + ) + self.target[0] = -0.06 + else: + # closed-finger hook from above, drag down the front face + sp = -0.95 + 0.62 * f + el = 0.05 + 0.15 * f + self._set_arms( + [sp, 0.45 * (1 - 0.3 * f), 0.0, el, 0.0, 0.25 * (1 - f), 0.0], + [sp, -0.45 * (1 - 0.3 * f), 0.0, el, 0.0, 0.25 * (1 - f), 0.0], + ) + self.target[0] = -0.05 + self._set_grip(g) + + # if the pan becomes visible, go straight to the search/grasp phase + if self.phase_t % 15 == 0: + c, cx, cy = self._find_pan(tools, full=True) + if c > 140: + self._advance(2) + return + if self.phase_t > 4 * n: + self.target[0] = 0.0 + self.target[4] = self.FACE_PITCH + self._advance(2) + + def _search(self, tools): + """Squat and sweep the right hand through the cabinet opening.""" + self.target[0] = 0.0 + self.target[1] = 0.0 + self.target[3] = 0.0 + self.target[2] = self.SQUAT_H + self.target[4] = 0.28 + poses = [ + (-0.72, 0.10, 0.55, 0.0), + (-0.88, 0.20, 0.35, 0.0), + (-1.02, 0.35, 0.15, 0.0), + (-0.94, 0.05, 0.20, 0.1), + (-0.80, 0.45, 0.30, -0.1), + (-1.10, 0.20, 0.10, 0.0), + ] + idx = (self.phase_t // 35) % len(poses) + sp, el, wp, wy = poses[idx] + self.target[5:12] = [sp, 0.10, 0.0, el, 0.0, wp, -wy] + self.target[12:19] = [sp, -0.10, 0.0, el, 0.0, wp, wy] + + c, cx, cy = self._find_pan(tools, full=(self.phase_t % 10 == 0)) + if self.pan_grab: + # the pan is held: stop servo-ing and lift it + self._advance(3) + return + if c > 45: + self.pan_seen += 1 + self._set_grip(0.0) + # steer the right hand towards the copper blob + if cx > 48: + self.target[13] += 0.025 + elif cx < 36: + self.target[13] -= 0.025 + if cy > 50: + self.target[12] += 0.020 + elif cy < 34: + self.target[12] -= 0.020 + if c < 220: + self.target[15] -= 0.012 + else: + self._set_grip(1.0) + self.pan_grab = True + else: + self._set_grip(0.0) + + if self.phase_t > 850: + # no pan found: try the door repertoire one more time, then place + if self.open_round < 1: + self.open_round += 1 + self._advance(1) + else: + self._advance(3) + + def _place(self, tools): + """Lift the pan over the hob and release it.""" + f = min(1.0, self.phase_t / 220.0) + sp = -0.75 - 0.35 * f + el = 0.20 + 0.30 * f + self.target[2] = 0.745 + 0.095 * f + self.target[4] = 0.15 + self.target[0] = 0.0 + self.target[1] = 0.0 + self.target[3] = 0.0 + self.target[12:19] = [sp, -0.10, 0.0, el, 0.0, 0.10, 0.0] + self.target[5:12] = [-0.60, 0.10, 0.0, 0.30, 0.0, 0.20, 0.0] + if self.phase_t < 220: + self._set_grip(1.0) + else: + self._set_grip(0.0) + + # ------------------------------------------------------------------ + def act(self, obs, tools): + self.t += 1 + self.phase_t += 1 + + # default: no base motion unless a phase commands it + self.target[0] = 0.0 + self.target[1] = 0.0 + self.target[3] = 0.0 + + if self.phase == 0: + self._walk_to_cabinet() + elif self.phase == 1: + self._opening(tools) + elif self.phase == 2: + self._search(tools) + else: + self._place(tools) + + return _clip_action(self.target) diff --git a/policies/saucepan_to_hob/gpt61sol-s1/episodes.csv b/policies/saucepan_to_hob/gpt61sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..ac0a317b41404d4e9097d329e0279bdf138f2960 --- /dev/null +++ b/policies/saucepan_to_hob/gpt61sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,1,3942,success,0 +620001,1,3946,success,0 +620002,1,4022,success,0 +620003,1,4018,success,0 +620004,1,4000,success,0 +620005,1,4025,success,0 +620006,1,3949,success,0 +620007,0,4650,timeout,0 +620008,1,3915,success,0 +620009,1,3950,success,0 +620010,1,3918,success,0 +620011,1,3949,success,0 +620012,1,4016,success,0 +620013,0,4650,timeout,0 +620014,0,4650,timeout,0 +620015,1,4025,success,0 +620016,1,4003,success,0 +620017,1,3962,success,0 +620018,1,4022,success,0 +620019,1,3948,success,0 +620020,1,4024,success,0 +620021,1,3988,success,0 +620022,1,3993,success,0 +620023,1,3916,success,0 +620024,1,3946,success,0 +620025,1,3948,success,0 +620026,1,3945,success,0 +620027,1,3949,success,0 +620028,1,4003,success,0 +620029,1,3978,success,0 +620030,0,4650,timeout,0 +620031,1,3916,success,0 +620032,0,4650,timeout,0 +620033,0,4650,timeout,0 +620034,1,4022,success,0 +620035,1,3947,success,0 +620036,1,4016,success,0 +620037,1,3946,success,0 +620038,1,3939,success,0 +620039,1,3944,success,0 +620040,1,4023,success,0 +620041,1,4023,success,0 +620042,1,3949,success,0 +620043,1,3943,success,0 +620044,1,3975,success,0 +620045,1,3964,success,0 +620046,1,4028,success,0 +620047,0,4650,timeout,0 +620048,1,3942,success,0 +620049,1,4022,success,0 +620050,0,4650,timeout,0 +620051,1,3924,success,0 +620052,0,4650,timeout,0 +620053,0,4650,timeout,0 +620054,1,3945,success,0 +620055,0,4650,timeout,0 +620056,0,4650,timeout,0 +620057,1,4015,success,0 +620058,1,3944,success,0 +620059,0,4650,timeout,0 +620060,1,3994,success,0 +620061,0,4650,timeout,0 +620062,0,4650,timeout,0 +620063,1,3948,success,0 +620064,1,3946,success,0 +620065,1,3944,success,0 +620066,0,4650,timeout,0 +620067,1,3945,success,0 +620068,1,4026,success,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,1,4018,success,0 +620073,1,4022,success,0 +620074,1,3947,success,0 +620075,1,3949,success,0 +620076,0,4650,timeout,0 +620077,1,3949,success,0 +620078,0,4650,timeout,0 +620079,1,3990,success,0 +620080,1,3949,success,0 +620081,1,3948,success,0 +620082,1,4021,success,0 +620083,1,3944,success,0 +620084,1,3919,success,0 +620085,1,4022,success,0 +620086,1,3942,success,0 +620087,0,4650,timeout,0 +620088,1,3950,success,0 +620089,0,4650,timeout,0 +620090,1,4023,success,0 +620091,1,4018,success,0 +620092,1,4022,success,0 +620093,0,4650,timeout,0 +620094,1,3949,success,0 +620095,1,4015,success,0 +620096,1,3986,success,0 +620097,1,4024,success,0 +620098,0,4650,timeout,0 +620099,1,3947,success,0 diff --git a/policies/saucepan_to_hob/gpt61sol-s1/policy.py b/policies/saucepan_to_hob/gpt61sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..fbbbe3c13a05031bafbd2ae87902f3c0c7d14754 --- /dev/null +++ b/policies/saucepan_to_hob/gpt61sol-s1/policy.py @@ -0,0 +1,117 @@ +"""Deterministic, hand-written cabinet opening and saucepan transfer. + +All scene measurements come from the robot's head camera. Base motion uses +pelvis feedback; arm motions interpolate between manually tuned joint poses. +""" + +import numpy as np +import cv2 + +class Policy: + def reset(self,obs,tools): + # Each episode starts from its own body state and fresh camera estimate. + self.a=np.asarray(tools.hold_action(),float);self.a[19:21]=0 + self.stage=0;self.age=0;self.begin=self.a.copy() + self.grasp_goal=[.44,.08,0] + def pose(self,updates,duration=90): + b=self.begin.copy() + for k,v in updates.items():b[k]=v + f=min(1,self.age/max(duration,1)) + self.a=self.begin+(b-self.begin)*f + def advance(self): + self.stage+=1;self.age=0;self.begin=self.a.copy();self.begin[0]=self.begin[1]=self.begin[3]=0 + def move(self,o,goal,speed=.10): + # World-frame position error, converted to body-frame velocity. + # Respect the walking controller's minimum effective speed. + p=o['low_dim_obs'][21:25];err=np.array(goal[:2])-p[:2];dy=(goal[2]-p[3]+np.pi)%(2*np.pi)-np.pi + vel=err*1.5 + if np.linalg.norm(vel)>speed:vel*=speed/np.linalg.norm(vel) + if np.linalg.norm(err)<.015:vel*=0 + elif np.linalg.norm(vel)<.07:vel*=.07/max(np.linalg.norm(vel),1e-6) + self.a[0]=np.cos(p[3])*vel[0]+np.sin(p[3])*vel[1] + self.a[1]=-np.sin(p[3])*vel[0]+np.cos(p[3])*vel[1] + self.a[3]=np.clip(dy*2,-.25,.25) + return self.age>80 and np.linalg.norm(err)<.025 and abs(dy)<.04 + def act(self,obs,tools): + self.age+=1;self.a[0]=self.a[1]=self.a[3]=0 + s=self.stage + # Clear the hands, approach the cabinet, and grasp its handle. + if s==0: + self.pose({5:.7,12:.7,19:0,20:0},80) + if self.age>100:self.advance() + elif s==1: + if self.move(obs,[.37,.09,0],.16) or self.age>450:self.advance() + elif s==2: + self.pose({5:.4},80) + if self.age>=100:self.advance() + elif s==3: + self.pose({19:1},25) + if self.age>=65:self.advance() + # Follow the door outward, then return around its free edge. + elif s==4: + if self.move(obs,[.03,-.16,0]) or self.age>320:self.advance() + elif s==5: + if self.move(obs,[-.08,-.4,0]) or self.age>300:self.advance() + elif s==6: + if self.move(obs,[.06,-.64,0]) or self.age>300:self.advance() + elif s==7: + self.pose({19:0},30) + if self.age>=80:self.advance() + elif s==8: + self.pose({5:1.2,12:1.2},80) + if self.age>=100:self.advance() + elif s==9: + if self.move(obs,[-.38,-.5,0],.18) or self.age>260:self.advance() + elif s==10: + if self.move(obs,[-.38,.08,0],.18) or self.age>350:self.advance() + elif s==11: + if self.move(obs,[.32,.08,0],.18) or self.age>400:self.advance() + # Copper colour locates the pan on the shelf before the close approach. + elif s==12: + if self.age==1: + im=tools.image("head").astype(float) + r,g,b=im[:,:,0],im[:,:,1],im[:,:,2] + mask=((r>1.35*g)&(g>1.05*b)&(r>55)).astype(np.uint8) + mask[:43]=0;mask[62:]=0;mask[:,:10]=0;mask[:,72:]=0 + n,labels,stats,centers=cv2.connectedComponentsWithStats(mask) + if n>1: + j=1+np.argmax(stats[1:,4]) + if stats[j,4]>8: + cx,cy=centers[j] + self.grasp_goal=[.44+float(np.clip((47-cy)*.005,-.055,.055)),.08+float(np.clip((41-cx)*.006,-.065,.065)),0] + self.move(obs,self.grasp_goal,.15) + if self.age>=250:self.advance() + elif s==13: + self.pose({2:.50,12:0,16:1.57,17:-.2,20:0},80) + if self.age>=100:self.advance() + elif s==14: + self.pose({2:.54,12:0,16:1.57,17:0,20:0},80) + if self.age>=130:self.advance() + elif s==15: + self.pose({20:1},30) + if self.age>=65:self.advance() + # Keep the handle orientation while drawing the pan below the counter. + elif s==16: + self.pose({12:.55,15:-.85,18:-.3},140) + if self.age>=170:self.advance() + elif s==17: + self.pose({2:.74,12:1.3,18:.45},150) + if self.age>=180:self.advance() + elif s==18: + if self.move(obs,[.15,.08,0],.12) or self.age>350:self.advance() + # Lift above the hob, approach, lower slowly, release, and clear the hand. + elif s==19: + self.pose({12:-.4,18:-1.25},150) + if self.age>=180:self.advance() + elif s==20: + if self.move(obs,[.48,-.09,-.18],.15) or self.age>330:self.advance() + elif s==21: + self.pose({12:-.1,18:-.95},100) + if self.age>=130:self.advance() + elif s==22: + self.pose({20:0},30) + if self.age>=100:self.advance() + elif s==23: + self.pose({12:.6,18:-.25,20:0},100) + if self.age>=140:self.advance() + return self.a.copy() diff --git a/policies/saucepan_to_hob/gpt61sol-s2/episodes.csv b/policies/saucepan_to_hob/gpt61sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8bdd4e6043da73ac776c1ce5081f089e7a50e206 --- /dev/null +++ b/policies/saucepan_to_hob/gpt61sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4650,timeout,0 +620001,0,4650,timeout,0 +620002,0,4650,timeout,0 +620003,0,4650,timeout,0 +620004,0,4650,timeout,0 +620005,0,4650,timeout,0 +620006,0,4650,timeout,0 +620007,0,4650,timeout,0 +620008,0,4650,timeout,0 +620009,0,4650,timeout,0 +620010,0,4650,timeout,0 +620011,0,4650,timeout,0 +620012,0,4650,timeout,0 +620013,0,4650,timeout,0 +620014,0,4650,timeout,0 +620015,0,4650,timeout,0 +620016,0,4650,timeout,0 +620017,0,4650,timeout,0 +620018,0,4650,timeout,0 +620019,0,4650,timeout,0 +620020,0,4650,timeout,0 +620021,0,4650,timeout,0 +620022,0,4650,timeout,0 +620023,0,4650,timeout,0 +620024,0,4650,timeout,0 +620025,0,4650,timeout,0 +620026,0,4650,timeout,0 +620027,0,4650,timeout,0 +620028,0,4650,timeout,0 +620029,0,4650,timeout,0 +620030,0,4650,timeout,0 +620031,0,4650,timeout,0 +620032,0,4650,timeout,0 +620033,0,4650,timeout,0 +620034,0,4650,timeout,0 +620035,0,4650,timeout,0 +620036,0,4650,timeout,0 +620037,0,4650,timeout,0 +620038,0,4650,timeout,0 +620039,0,4650,timeout,0 +620040,0,4650,timeout,0 +620041,0,4650,timeout,0 +620042,0,4650,timeout,0 +620043,0,4650,timeout,0 +620044,0,4650,timeout,0 +620045,0,4650,timeout,0 +620046,0,4650,timeout,0 +620047,0,4650,timeout,0 +620048,0,4650,timeout,0 +620049,0,4650,timeout,0 +620050,0,4650,timeout,0 +620051,0,4650,timeout,0 +620052,0,4650,timeout,0 +620053,0,4650,timeout,0 +620054,0,4650,timeout,0 +620055,0,4650,timeout,0 +620056,0,4650,timeout,0 +620057,0,4650,timeout,0 +620058,0,4650,timeout,0 +620059,0,4650,timeout,0 +620060,0,4650,timeout,0 +620061,0,4650,timeout,0 +620062,0,4650,timeout,0 +620063,0,4650,timeout,0 +620064,0,4650,timeout,0 +620065,0,4650,timeout,0 +620066,0,4650,timeout,0 +620067,0,4650,timeout,0 +620068,0,4650,timeout,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,0,4650,timeout,0 +620073,0,4650,timeout,0 +620074,0,4650,timeout,0 +620075,0,4650,timeout,0 +620076,0,4650,timeout,0 +620077,0,4650,timeout,0 +620078,0,4650,timeout,0 +620079,0,4650,timeout,0 +620080,0,4650,timeout,0 +620081,0,4650,timeout,0 +620082,0,4650,timeout,0 +620083,0,4650,timeout,0 +620084,0,4650,timeout,0 +620085,0,4650,timeout,0 +620086,0,4650,timeout,0 +620087,0,4650,timeout,0 +620088,0,4650,timeout,0 +620089,0,4650,timeout,0 +620090,0,4650,timeout,0 +620091,0,4650,timeout,0 +620092,0,4650,timeout,0 +620093,0,4650,timeout,0 +620094,0,4650,timeout,0 +620095,0,4650,timeout,0 +620096,0,4650,timeout,0 +620097,0,4650,timeout,0 +620098,0,4650,timeout,0 +620099,0,4650,timeout,0 diff --git a/policies/saucepan_to_hob/gpt61sol-s2/policy.py b/policies/saucepan_to_hob/gpt61sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a59122520ef1010b17f17b16c5da1c44be221d81 --- /dev/null +++ b/policies/saucepan_to_hob/gpt61sol-s2/policy.py @@ -0,0 +1,107 @@ +"""Deterministic cabinet, grasp, and saucepan transfer controller.""" +import numpy as np + +class Policy: + def reset(self, obs, tools): + self.stage=0; self.start=obs['t']; self.grasped=False + self.contact_count=0; self.saved=None + self.stages=[(200,(.4,-.05,.2)),(40,None),(120,(.15,-.12,.2)), + (140,(-.05,-.3,.2)),(140,(-.12,-.55,.2)),(180,(-.08,-.82,.2)), + (100,(-.3,-.75,0)),(350,(-.3,.45,0)),(180,(.3,.45,0)), + (120,(.3,.2,0)),(80,None),(80,None),(60,None),(70,None)] + self.a=np.asarray(tools.hold_action(),dtype=float) + def navigate(self,a,obs,target,speed=.22): + x,y,_,yaw=obs['low_dim_obs'][21:25];tx,ty,tw=target + error=np.array([tx-x,ty-y]);distance=float(np.linalg.norm(error)) + velocity=np.zeros(2) if distance<.02 else error/distance*min(speed,max(.065,1.2*distance)) + 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(1.8*((tw-yaw+np.pi)%(2*np.pi)-np.pi),-.4,.4) + def advance(self,t,stage=None): + self.stage=self.stage+1 if stage is None else stage;self.start=t + def act(self,obs,tools): + t=obs['t'];elapsed=t-self.start;a=self.a.copy() + a[:5]=[0,0,.74,0,0] + a[5:12]=[.32,.5,0,0,-.5,0,0] + a[12:19]=[0,-.5,0,1,0,0,0];a[19:21]=[0,0] + if self.stage<14: + duration,target=self.stages[self.stage] + if self.stage>=1:a[19]=1 + if self.stage>=6: + a[5:12]=[.2,.5,0,1,0,0,0];a[19]=0 + if self.stage>=8: + a[5:12]=[.3,1,0,1.5,0,0,0] + a[12:19]=[.3,-.3,0,1.5,1.57,0,0];a[20]=1 + if self.stage>=11:a[2]=.59 + if self.stage==12:a[12:19]=[.8,0,0,-.9,1.57,0,0] + if self.stage==13: + a[12:19]=[-1,-.05,0,1.1,1.57,0,-.35];a[20]=.4 + if target is not None:self.navigate(a,obs,target,.30 if self.stage>=7 else .22) + if elapsed>=duration:self.advance(t) + elif self.stage in (14,31): + a[5:12]=[.3,1,0,1.5,0,0,0] + attempt=elapsed//160;phase=elapsed%160 + nominal=.59 if self.stage==14 else .55 + offset=0 if attempt%3==0 else (.02 if attempt%3==1 else -.02) + a[2]=nominal+offset + a[12:19]=[-1,-.05,0,1.1,1.57,0,-.35] + a[20]=.4 if phase<90 else 1 + if phase>=120: + fingers=obs['low_dim_obs'][19:21] + contact=float(np.sum(fingers))>-.035 and float(np.min(fingers))>-.0195 and float(np.max(fingers))<.015 + self.contact_count=self.contact_count+1 if contact else 0 + if self.contact_count>=6: + im=tools.image('right_wrist').astype(np.int16) + patch=im[10:80,28:57] + gold=(patch[:,:,0]>140)&(patch[:,:,0]>1.08*patch[:,:,1])&(patch[:,:,1]>1.35*patch[:,:,2]) + if np.count_nonzero(gold)>=6: + self.saved=a.copy();self.grasped=True;self.advance(t,20) + if self.stage==14 and elapsed>=480: + self.contact_count=0;self.advance(t,15) + elif self.stage in (15,16,17,18,19,30): + # A second approach reaches the outer part of the handle. + a[5:12]=[.3,1,0,1.5,0,0,0] + a[12:19]=[.3,-.3,0,1.5,1.57,0,0];a[20]=1 + if self.stage==15: + if elapsed<45: + a[2]=.59;a[12:19]=[.8,0,0,-.9,1.57,0,0];a[20]=0 + if elapsed>=140:self.advance(t) + elif self.stage==16: + self.navigate(a,obs,(.30,.10,0),.15) + if elapsed>=170:self.advance(t) + elif self.stage==17: + if elapsed>=90:self.advance(t) + elif self.stage==18: + a[2]=.55 + if elapsed>=90:self.advance(t) + elif self.stage==19: + a[2]=.55;a[12:19]=[.8,0,0,-.9,1.57,0,0] + if elapsed>=70:self.advance(t,30) + else: + a[2]=.55;a[12:19]=[-1,-.05,0,1.1,1.57,0,-.35];a[20]=.4 + if elapsed>=90:self.advance(t,31) + else: + a=self.saved.copy();a[:2]=0;a[3]=0;a[20]=1 + if self.stage==20: + f=min(1,elapsed/90);a[2]=self.saved[2]+.015*f + a[12]=-1+1.5*f;a[15]=1.1-2.1*f;a[18]=-.35-.6*f + if elapsed>=120:self.advance(t) + elif self.stage==21: + f=min(1,elapsed/90);a[2]=(1-f)*(self.saved[2]+.015)+f*.74 + a[12:19]=[.5,-.05,0,-1,1.57,0,-.95] + if elapsed>=120:self.advance(t) + elif self.stage==22: + f=min(1,elapsed/90);a[2]=.74+.04*f + a[12:19]=[.5-2.1*f,-.05,0,-1+2.1*f,1.57,0,-.95] + if elapsed>=100:self.advance(t) + elif self.stage==23: + a[2]=.78;a[12:19]=[-1.6,-.05,0,1.1,1.57,0,-.95] + self.navigate(a,obs,(.5,.2,0),.12) + if elapsed>=180:self.advance(t) + elif self.stage==24: + f=min(1,elapsed/120);a[2]=.78-.04*f + a[12:19]=[-1.6+.65*f,-.05,0,1.1-.65*f,1.57,0,-.95] + if elapsed>=150:self.advance(t) + else: + a[2]=.74;a[12:19]=[-.95,-.05,0,.45,1.57,0,-.95];a[20]=0 + self.a=a.copy();return a.astype(np.float32) diff --git a/policies/saucepan_to_hob/gpt61sol-s3/episodes.csv b/policies/saucepan_to_hob/gpt61sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8bdd4e6043da73ac776c1ce5081f089e7a50e206 --- /dev/null +++ b/policies/saucepan_to_hob/gpt61sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4650,timeout,0 +620001,0,4650,timeout,0 +620002,0,4650,timeout,0 +620003,0,4650,timeout,0 +620004,0,4650,timeout,0 +620005,0,4650,timeout,0 +620006,0,4650,timeout,0 +620007,0,4650,timeout,0 +620008,0,4650,timeout,0 +620009,0,4650,timeout,0 +620010,0,4650,timeout,0 +620011,0,4650,timeout,0 +620012,0,4650,timeout,0 +620013,0,4650,timeout,0 +620014,0,4650,timeout,0 +620015,0,4650,timeout,0 +620016,0,4650,timeout,0 +620017,0,4650,timeout,0 +620018,0,4650,timeout,0 +620019,0,4650,timeout,0 +620020,0,4650,timeout,0 +620021,0,4650,timeout,0 +620022,0,4650,timeout,0 +620023,0,4650,timeout,0 +620024,0,4650,timeout,0 +620025,0,4650,timeout,0 +620026,0,4650,timeout,0 +620027,0,4650,timeout,0 +620028,0,4650,timeout,0 +620029,0,4650,timeout,0 +620030,0,4650,timeout,0 +620031,0,4650,timeout,0 +620032,0,4650,timeout,0 +620033,0,4650,timeout,0 +620034,0,4650,timeout,0 +620035,0,4650,timeout,0 +620036,0,4650,timeout,0 +620037,0,4650,timeout,0 +620038,0,4650,timeout,0 +620039,0,4650,timeout,0 +620040,0,4650,timeout,0 +620041,0,4650,timeout,0 +620042,0,4650,timeout,0 +620043,0,4650,timeout,0 +620044,0,4650,timeout,0 +620045,0,4650,timeout,0 +620046,0,4650,timeout,0 +620047,0,4650,timeout,0 +620048,0,4650,timeout,0 +620049,0,4650,timeout,0 +620050,0,4650,timeout,0 +620051,0,4650,timeout,0 +620052,0,4650,timeout,0 +620053,0,4650,timeout,0 +620054,0,4650,timeout,0 +620055,0,4650,timeout,0 +620056,0,4650,timeout,0 +620057,0,4650,timeout,0 +620058,0,4650,timeout,0 +620059,0,4650,timeout,0 +620060,0,4650,timeout,0 +620061,0,4650,timeout,0 +620062,0,4650,timeout,0 +620063,0,4650,timeout,0 +620064,0,4650,timeout,0 +620065,0,4650,timeout,0 +620066,0,4650,timeout,0 +620067,0,4650,timeout,0 +620068,0,4650,timeout,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,0,4650,timeout,0 +620073,0,4650,timeout,0 +620074,0,4650,timeout,0 +620075,0,4650,timeout,0 +620076,0,4650,timeout,0 +620077,0,4650,timeout,0 +620078,0,4650,timeout,0 +620079,0,4650,timeout,0 +620080,0,4650,timeout,0 +620081,0,4650,timeout,0 +620082,0,4650,timeout,0 +620083,0,4650,timeout,0 +620084,0,4650,timeout,0 +620085,0,4650,timeout,0 +620086,0,4650,timeout,0 +620087,0,4650,timeout,0 +620088,0,4650,timeout,0 +620089,0,4650,timeout,0 +620090,0,4650,timeout,0 +620091,0,4650,timeout,0 +620092,0,4650,timeout,0 +620093,0,4650,timeout,0 +620094,0,4650,timeout,0 +620095,0,4650,timeout,0 +620096,0,4650,timeout,0 +620097,0,4650,timeout,0 +620098,0,4650,timeout,0 +620099,0,4650,timeout,0 diff --git a/policies/saucepan_to_hob/gpt61sol-s3/policy.py b/policies/saucepan_to_hob/gpt61sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..cd1f61a3b6bc67eb4fa7ff84feb9d1ea599d71c6 --- /dev/null +++ b/policies/saucepan_to_hob/gpt61sol-s3/policy.py @@ -0,0 +1,85 @@ +"""Deterministic staged control using proprioception and the robot cameras.""" +import numpy as np +import cv2 + +class Policy: + def reset(self,obs,tools): + self.a=np.array(tools.hold_action(),float);self.a[19:]=0 + tuck=[0,0,0,1,0,0,0];clear=[.8,.5,.5,.6,0,0,0] + self.stages=[ + ('tuck',50,{5:tuck,12:tuck}), + ('approach',130,{},(.28,-.025),0), + ('settle',30,{}),('lower',70,{2:.66}), + ('handle',80,{5:[.075,.3,.2,0,0,0,0]}),('align',40,{}),('close',40,{19:1}), + ('pull',160,{2:.65,5:[.8,.3,.2,-.4,0,-.3,0]}),('pause',30,{}), + ('open',160,{2:.74,5:[.8,.3,.05,.2,0,-.9,-.05]}),('pause2',30,{}), + ('draw_back',90,{},None,0,(-.12,-.08)),('stop',40,{}), + ('release_door',90,{5:clear,19:0}), + ('back_clear',180,{},(-.1,-.16),0), + ('walk_left',400,{},(-.1,.65),0), + ('along_side',400,{},(.60,.65),0), + ('turn_side',180,{},None,-1.2), + ('side_approach',180,{},(.58,.38),-1.2), + ('stop_side',40,{},None,-1.2), + ('squat',160,{2:.50,4:.3},None,-1.2), + ('reach_low',180,{12:[-.8,-.1,.1,.6,1.5,-.3,.05]},None,-1.2), + ('reach_hold',240,{},None,-1.2),('grasp_pan',45,{20:1},None,-1.2), + ('capture',160,{2:.45,4:.4},None,-1.2), + ('extract_pan',140,{2:.60,4:.15,12:.35,15:.6},None,-1.2), + ('lift',180,{2:.78,4:0,12:[-1.2,-.1,.1,.5,1.5,-.1,.05]},None,-1.2), + ('carry_align',180,{},(.58,.38),-1.2), + ('place',180,{2:.74,12:[-1.1,-.1,.1,.65,1.5,-.1,.05]},None,-1.2), + ('release_pan',80,{20:0},None,-1.2), + ('withdraw',140,{12:[0,0,0,1,0,0,0]},None,-1.2),('rest',300,{},None,-1.2)] + self.i=0;self.k=0;self.near=0;self.begin() + def begin(self): + stage=self.stages[self.i];self.start=self.a.copy();self.end=self.a.copy();self.end[:2]=0 + for ind,val in stage[2].items(): + if isinstance(val,list):self.end[ind:ind+len(val)]=val + else:self.end[ind]=val + self.k=0;self.near=0;self.servo=self.a[17:19].copy() + # Locate the narrow gold handle against the gray cabinet interior. + def handle_pixel(self,tools): + im=tools.image('right_wrist').astype(float);r,g,b=im[:,:,0],im[:,:,1],im[:,:,2] + mask=((r>120)&(g>90)&(g>.65*r)&(g<.91*r)&(b<.8*g)).astype(np.uint8) + count,labels,stats,centers=cv2.connectedComponentsWithStats(mask) + candidates=[] + for stat,center in zip(stats[1:],centers[1:]): + x,y,w,h,area=stat + if 7<=area<=180 and max(w,h)>=10 and max(w,h)>2*min(w,h): + candidates.append((np.linalg.norm(center-[42,48]),center)) + return min(candidates,key=lambda v:v[0])[1] if candidates else None + def act(self,obs,tools): + stage=self.stages[self.i];name,n=stage[:2];self.phase=name + self.k+=1;u=min(1,self.k/n) + if name in ("tuck","lower","close","grasp_pan","release_pan"):u=1 + self.a=self.start+(self.end-self.start)*u + self.a[:2]=0 + # Small wrist corrections put the handle between the open fingers. + if name=='reach_hold': + if self.k%8==0: + pixel=self.handle_pixel(tools) + if pixel is not None: + self.servo[0]+=np.clip((pixel[1]-48)*.003,-.025,.025) + self.servo[1]+=np.clip((42-pixel[0])*.003,-.025,.025) + self.servo=np.clip(self.servo,-1.2,1.2) + self.a[17:19]=self.servo + p=obs['low_dim_obs'][21:25];yaw=stage[4] if len(stage)>4 else 0 + dyaw=(yaw-p[3]+np.pi)%(2*np.pi)-np.pi;self.a[3]=np.clip(dyaw*3,-.5,.5) + reached=False + if len(stage)>3 and stage[3] is not None: + err=np.array(stage[3])-p[:2];c,s=np.cos(p[3]),np.sin(p[3]);v=np.array([[c,s],[-s,c]])@err*2.5 + if np.linalg.norm(err)<.018:v*=0;self.near+=1 + else: + self.near=0 + if np.linalg.norm(v)<.065:v=v/max(np.linalg.norm(v),1e-9)*.065 + self.a[:2]=np.clip(v,-.15,.15);reached=np.linalg.norm(err)<.025 and self.k>46 and abs(dyaw)<.06 + if name=="approach": + v=np.array([[c,s],[-s,c]])@err*2.5 + if np.linalg.norm(v)<.06:v*=0 + self.a[:2]=np.clip(v,-.15,.15);reached=np.linalg.norm(err)<.012 and self.k>45 + if len(stage)>5:self.a[:2]=stage[5] + result=self.a.copy() + if self.k>=n or reached: + if self.i= self.phases[self.phase][0]: + self.phase_start += self.phases[self.phase][0] + self.phase += 1 + for k,v in self.phases[self.phase][1].items(): self.action[k]=v + return self.action.copy() diff --git a/policies/saucepan_to_hob/gpt61terra-s2/episodes.csv b/policies/saucepan_to_hob/gpt61terra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8bdd4e6043da73ac776c1ce5081f089e7a50e206 --- /dev/null +++ b/policies/saucepan_to_hob/gpt61terra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4650,timeout,0 +620001,0,4650,timeout,0 +620002,0,4650,timeout,0 +620003,0,4650,timeout,0 +620004,0,4650,timeout,0 +620005,0,4650,timeout,0 +620006,0,4650,timeout,0 +620007,0,4650,timeout,0 +620008,0,4650,timeout,0 +620009,0,4650,timeout,0 +620010,0,4650,timeout,0 +620011,0,4650,timeout,0 +620012,0,4650,timeout,0 +620013,0,4650,timeout,0 +620014,0,4650,timeout,0 +620015,0,4650,timeout,0 +620016,0,4650,timeout,0 +620017,0,4650,timeout,0 +620018,0,4650,timeout,0 +620019,0,4650,timeout,0 +620020,0,4650,timeout,0 +620021,0,4650,timeout,0 +620022,0,4650,timeout,0 +620023,0,4650,timeout,0 +620024,0,4650,timeout,0 +620025,0,4650,timeout,0 +620026,0,4650,timeout,0 +620027,0,4650,timeout,0 +620028,0,4650,timeout,0 +620029,0,4650,timeout,0 +620030,0,4650,timeout,0 +620031,0,4650,timeout,0 +620032,0,4650,timeout,0 +620033,0,4650,timeout,0 +620034,0,4650,timeout,0 +620035,0,4650,timeout,0 +620036,0,4650,timeout,0 +620037,0,4650,timeout,0 +620038,0,4650,timeout,0 +620039,0,4650,timeout,0 +620040,0,4650,timeout,0 +620041,0,4650,timeout,0 +620042,0,4650,timeout,0 +620043,0,4650,timeout,0 +620044,0,4650,timeout,0 +620045,0,4650,timeout,0 +620046,0,4650,timeout,0 +620047,0,4650,timeout,0 +620048,0,4650,timeout,0 +620049,0,4650,timeout,0 +620050,0,4650,timeout,0 +620051,0,4650,timeout,0 +620052,0,4650,timeout,0 +620053,0,4650,timeout,0 +620054,0,4650,timeout,0 +620055,0,4650,timeout,0 +620056,0,4650,timeout,0 +620057,0,4650,timeout,0 +620058,0,4650,timeout,0 +620059,0,4650,timeout,0 +620060,0,4650,timeout,0 +620061,0,4650,timeout,0 +620062,0,4650,timeout,0 +620063,0,4650,timeout,0 +620064,0,4650,timeout,0 +620065,0,4650,timeout,0 +620066,0,4650,timeout,0 +620067,0,4650,timeout,0 +620068,0,4650,timeout,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,0,4650,timeout,0 +620073,0,4650,timeout,0 +620074,0,4650,timeout,0 +620075,0,4650,timeout,0 +620076,0,4650,timeout,0 +620077,0,4650,timeout,0 +620078,0,4650,timeout,0 +620079,0,4650,timeout,0 +620080,0,4650,timeout,0 +620081,0,4650,timeout,0 +620082,0,4650,timeout,0 +620083,0,4650,timeout,0 +620084,0,4650,timeout,0 +620085,0,4650,timeout,0 +620086,0,4650,timeout,0 +620087,0,4650,timeout,0 +620088,0,4650,timeout,0 +620089,0,4650,timeout,0 +620090,0,4650,timeout,0 +620091,0,4650,timeout,0 +620092,0,4650,timeout,0 +620093,0,4650,timeout,0 +620094,0,4650,timeout,0 +620095,0,4650,timeout,0 +620096,0,4650,timeout,0 +620097,0,4650,timeout,0 +620098,0,4650,timeout,0 +620099,0,4650,timeout,0 diff --git a/policies/saucepan_to_hob/gpt61terra-s2/policy.py b/policies/saucepan_to_hob/gpt61terra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..1cbf920e8a6274d4021b80532023e00e6bca2548 --- /dev/null +++ b/policies/saucepan_to_hob/gpt61terra-s2/policy.py @@ -0,0 +1,52 @@ +"""Deterministic upper-body controller for the saucepan task.""" +import numpy as np + +class Policy: + def reset(self, obs, tools): + self.start = np.asarray(obs['low_dim_obs'][21:25], dtype=float).copy() + self.base = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = 0 + self.since = 0 + + def act(self, obs, tools): + t = int(obs['t']) + a = self.base.copy() + a[19:21] = 0 + # Move the left hand to the cabinet's free edge before squatting. + if t < 40: + a[1] = .2 + elif t < 80: + pass + elif t < 200: + a[2] = .52; a[5] = -.3 + elif t < 260: + a[2] = .52; a[5] = -.3; a[19] = 1 + elif t < 360: + a[2] = .52; a[5] = .2; a[19] = 1 + elif t < 470: + a[2] = .74; a[5] = .2; a[19] = 1 + elif t < 560: + a[2] = .74; a[5] = .2; a[19] = 1 + a[0] = -.08; a[1] = -.08 + elif t < 620: + a[5] = .2 + elif t < 720: + if t < 655: + a[1] = -.12 + elif t < 850: + a[2] = .53; a[12] = -.3 + elif t < 920: + a[2] = .53; a[12] = -.3; a[20] = 1 + elif t < 1050: + a[2] = .53; a[12] = -.8; a[20] = 1 + elif t < 1190: + a[2] = .74; a[12] = -.8; a[20] = 1 + elif t < 1320: + a[12] = -1.25; a[20] = 1 + elif t < 1440: + a[12] = -1.25; a[20] = 1; a[0] = .08 + elif t < 1500: + a[12] = -1.25 + else: + a[12] = -.5 + return a diff --git a/policies/saucepan_to_hob/gpt61terra-s3/episodes.csv b/policies/saucepan_to_hob/gpt61terra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8bdd4e6043da73ac776c1ce5081f089e7a50e206 --- /dev/null +++ b/policies/saucepan_to_hob/gpt61terra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4650,timeout,0 +620001,0,4650,timeout,0 +620002,0,4650,timeout,0 +620003,0,4650,timeout,0 +620004,0,4650,timeout,0 +620005,0,4650,timeout,0 +620006,0,4650,timeout,0 +620007,0,4650,timeout,0 +620008,0,4650,timeout,0 +620009,0,4650,timeout,0 +620010,0,4650,timeout,0 +620011,0,4650,timeout,0 +620012,0,4650,timeout,0 +620013,0,4650,timeout,0 +620014,0,4650,timeout,0 +620015,0,4650,timeout,0 +620016,0,4650,timeout,0 +620017,0,4650,timeout,0 +620018,0,4650,timeout,0 +620019,0,4650,timeout,0 +620020,0,4650,timeout,0 +620021,0,4650,timeout,0 +620022,0,4650,timeout,0 +620023,0,4650,timeout,0 +620024,0,4650,timeout,0 +620025,0,4650,timeout,0 +620026,0,4650,timeout,0 +620027,0,4650,timeout,0 +620028,0,4650,timeout,0 +620029,0,4650,timeout,0 +620030,0,4650,timeout,0 +620031,0,4650,timeout,0 +620032,0,4650,timeout,0 +620033,0,4650,timeout,0 +620034,0,4650,timeout,0 +620035,0,4650,timeout,0 +620036,0,4650,timeout,0 +620037,0,4650,timeout,0 +620038,0,4650,timeout,0 +620039,0,4650,timeout,0 +620040,0,4650,timeout,0 +620041,0,4650,timeout,0 +620042,0,4650,timeout,0 +620043,0,4650,timeout,0 +620044,0,4650,timeout,0 +620045,0,4650,timeout,0 +620046,0,4650,timeout,0 +620047,0,4650,timeout,0 +620048,0,4650,timeout,0 +620049,0,4650,timeout,0 +620050,0,4650,timeout,0 +620051,0,4650,timeout,0 +620052,0,4650,timeout,0 +620053,0,4650,timeout,0 +620054,0,4650,timeout,0 +620055,0,4650,timeout,0 +620056,0,4650,timeout,0 +620057,0,4650,timeout,0 +620058,0,4650,timeout,0 +620059,0,4650,timeout,0 +620060,0,4650,timeout,0 +620061,0,4650,timeout,0 +620062,0,4650,timeout,0 +620063,0,4650,timeout,0 +620064,0,4650,timeout,0 +620065,0,4650,timeout,0 +620066,0,4650,timeout,0 +620067,0,4650,timeout,0 +620068,0,4650,timeout,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,0,4650,timeout,0 +620073,0,4650,timeout,0 +620074,0,4650,timeout,0 +620075,0,4650,timeout,0 +620076,0,4650,timeout,0 +620077,0,4650,timeout,0 +620078,0,4650,timeout,0 +620079,0,4650,timeout,0 +620080,0,4650,timeout,0 +620081,0,4650,timeout,0 +620082,0,4650,timeout,0 +620083,0,4650,timeout,0 +620084,0,4650,timeout,0 +620085,0,4650,timeout,0 +620086,0,4650,timeout,0 +620087,0,4650,timeout,0 +620088,0,4650,timeout,0 +620089,0,4650,timeout,0 +620090,0,4650,timeout,0 +620091,0,4650,timeout,0 +620092,0,4650,timeout,0 +620093,0,4650,timeout,0 +620094,0,4650,timeout,0 +620095,0,4650,timeout,0 +620096,0,4650,timeout,0 +620097,0,4650,timeout,0 +620098,0,4650,timeout,0 +620099,0,4650,timeout,0 diff --git a/policies/saucepan_to_hob/gpt61terra-s3/policy.py b/policies/saucepan_to_hob/gpt61terra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..8c56f0fb636678f76d30e4bdae0f2b7dc7009328 --- /dev/null +++ b/policies/saucepan_to_hob/gpt61terra-s3/policy.py @@ -0,0 +1,40 @@ +"""Deterministic staged controller for the cabinet and saucepan task.""" +import numpy as np + +class Policy: + def reset(self, obs, tools): + self.initial = np.asarray(tools.hold_action(), dtype=np.float32) + self.start_x = float(obs['low_dim_obs'][21]) + self.phase = 0 + self.since = 0 + + def act(self, obs, tools): + t = int(obs['t']) + a = self.initial.copy() + a[2] = .74 + a[19:21] = 0 + # Reach the upper edge of the cabinet, close the hands, and pull. + if t < 400: + a[5:12] = [-.35, .10, 0, 0, 1.4, 0, 0] + a[12:19] = [-.35, -.10, 0, 0, -1.4, 0, 0] + if t >= 100: + a[19:21] = 1 + if 170 <= t < 290 and obs['low_dim_obs'][21] > self.start_x - .28: + a[0] = -.12 + # Reach down towards the handle and close the right hand. + elif t < 800: + a[2] = .65 + a[4] = .25 + a[12:19] = [-.75, -.15, 0, 1., 0, 0, 0] + if t >= 650: + a[20] = 1 + # Lift and position the held item above the hob. + elif t < 1300: + a[2] = .74 + a[12:19] = [-1.35, -.15, 0, .8, 0, 0, 0] + a[20] = 1 + if 950 <= t < 1100 and obs['low_dim_obs'][21] < self.start_x: + a[0] = .10 + else: + a[12:19] = [-1.35, -.15, 0, .8, 0, 0, 0] + return a diff --git a/policies/saucepan_to_hob/gpt6sol-s1/episodes.csv b/policies/saucepan_to_hob/gpt6sol-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8bdd4e6043da73ac776c1ce5081f089e7a50e206 --- /dev/null +++ b/policies/saucepan_to_hob/gpt6sol-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4650,timeout,0 +620001,0,4650,timeout,0 +620002,0,4650,timeout,0 +620003,0,4650,timeout,0 +620004,0,4650,timeout,0 +620005,0,4650,timeout,0 +620006,0,4650,timeout,0 +620007,0,4650,timeout,0 +620008,0,4650,timeout,0 +620009,0,4650,timeout,0 +620010,0,4650,timeout,0 +620011,0,4650,timeout,0 +620012,0,4650,timeout,0 +620013,0,4650,timeout,0 +620014,0,4650,timeout,0 +620015,0,4650,timeout,0 +620016,0,4650,timeout,0 +620017,0,4650,timeout,0 +620018,0,4650,timeout,0 +620019,0,4650,timeout,0 +620020,0,4650,timeout,0 +620021,0,4650,timeout,0 +620022,0,4650,timeout,0 +620023,0,4650,timeout,0 +620024,0,4650,timeout,0 +620025,0,4650,timeout,0 +620026,0,4650,timeout,0 +620027,0,4650,timeout,0 +620028,0,4650,timeout,0 +620029,0,4650,timeout,0 +620030,0,4650,timeout,0 +620031,0,4650,timeout,0 +620032,0,4650,timeout,0 +620033,0,4650,timeout,0 +620034,0,4650,timeout,0 +620035,0,4650,timeout,0 +620036,0,4650,timeout,0 +620037,0,4650,timeout,0 +620038,0,4650,timeout,0 +620039,0,4650,timeout,0 +620040,0,4650,timeout,0 +620041,0,4650,timeout,0 +620042,0,4650,timeout,0 +620043,0,4650,timeout,0 +620044,0,4650,timeout,0 +620045,0,4650,timeout,0 +620046,0,4650,timeout,0 +620047,0,4650,timeout,0 +620048,0,4650,timeout,0 +620049,0,4650,timeout,0 +620050,0,4650,timeout,0 +620051,0,4650,timeout,0 +620052,0,4650,timeout,0 +620053,0,4650,timeout,0 +620054,0,4650,timeout,0 +620055,0,4650,timeout,0 +620056,0,4650,timeout,0 +620057,0,4650,timeout,0 +620058,0,4650,timeout,0 +620059,0,4650,timeout,0 +620060,0,4650,timeout,0 +620061,0,4650,timeout,0 +620062,0,4650,timeout,0 +620063,0,4650,timeout,0 +620064,0,4650,timeout,0 +620065,0,4650,timeout,0 +620066,0,4650,timeout,0 +620067,0,4650,timeout,0 +620068,0,4650,timeout,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,0,4650,timeout,0 +620073,0,4650,timeout,0 +620074,0,4650,timeout,0 +620075,0,4650,timeout,0 +620076,0,4650,timeout,0 +620077,0,4650,timeout,0 +620078,0,4650,timeout,0 +620079,0,4650,timeout,0 +620080,0,4650,timeout,0 +620081,0,4650,timeout,0 +620082,0,4650,timeout,0 +620083,0,4650,timeout,0 +620084,0,4650,timeout,0 +620085,0,4650,timeout,0 +620086,0,4650,timeout,0 +620087,0,4650,timeout,0 +620088,0,4650,timeout,0 +620089,0,4650,timeout,0 +620090,0,4650,timeout,0 +620091,0,4650,timeout,0 +620092,0,4650,timeout,0 +620093,0,4650,timeout,0 +620094,0,4650,timeout,0 +620095,0,4650,timeout,0 +620096,0,4650,timeout,0 +620097,0,4650,timeout,0 +620098,0,4650,timeout,0 +620099,0,4650,timeout,0 diff --git a/policies/saucepan_to_hob/gpt6sol-s1/policy.py b/policies/saucepan_to_hob/gpt6sol-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2f872ce70a95285258319b6bf463e6e99ef0bf73 --- /dev/null +++ b/policies/saucepan_to_hob/gpt6sol-s1/policy.py @@ -0,0 +1,133 @@ +"""Deterministic hand-written G1 saucepan controller.""" + +import math +import numpy as np + + +def drive(a, obs, tx, ty, target_yaw=0.0, speed=0.16): + x, y, _, yaw = obs["low_dim_obs"][21:25] + dx, dy = tx - x, ty - y + forward = math.cos(yaw) * dx + math.sin(yaw) * dy + left = -math.sin(yaw) * dx + math.cos(yaw) * dy + if abs(forward) > 0.035: + a[0] = math.copysign(max(0.065, min(speed, 1.5 * abs(forward))), forward) + if abs(left) > 0.035: + a[1] = math.copysign(max(0.065, min(speed, 1.5 * abs(left))), left) + turn = (target_yaw - yaw + math.pi) % (2 * math.pi) - math.pi + if abs(turn) > 0.05: + a[3] = float(np.clip(2 * turn, -0.4, 0.4)) + + +class Policy: + def reset(self, obs, tools): + self.base = np.asarray(tools.hold_action(), dtype=np.float32) + self.grasp_at = None + # height, shoulder pitch/roll/yaw, elbow, torso pitch, base x/y + self.candidates = [ + (0.74, 0.0, 0.0, 0.0, 0.0, 0.0, 0.45, 0.50), + (0.70, 0.0, 0.0, 0.0, 0.0, 0.0, 0.45, 0.50), + (0.66, 0.0, 0.0, 0.0, 0.0, 0.0, 0.45, 0.50), + (0.74, 0.0, 0.0, 0.1, 0.0, 0.0, 0.45, 0.50), + (0.70, 0.0, 0.0, 0.1, 0.0, 0.0, 0.45, 0.50), + (0.74, 0.0, 0.0, 0.0, 0.3, 0.0, 0.45, 0.50), + (0.70, 0.0, 0.0, 0.0, 0.3, 0.0, 0.45, 0.50), + (0.74, -0.1, 0.0, 0.0, 0.0, 0.0, 0.45, 0.50), + (0.74, 0.1, 0.0, 0.0, 0.0, 0.0, 0.45, 0.50), + (0.74, 0.0, -0.1, 0.0, 0.0, 0.0, 0.45, 0.50), + (0.74, 0.0, 0.1, 0.0, 0.0, 0.0, 0.45, 0.50), + (0.74, 0.0, 0.0, 0.0, 0.0, 0.0, 0.40, 0.55), + (0.70, 0.0, 0.0, 0.0, 0.0, 0.0, 0.40, 0.55), + (0.74, 0.0, 0.0, 0.0, 0.0, 0.0, 0.48, 0.46), + (0.70, 0.0, 0.0, 0.0, 0.0, 0.0, 0.48, 0.46), + ] + + def act(self, obs, tools): + t = int(obs["t"]) + a = self.base.copy() + x, y = obs["low_dim_obs"][21:23] + + # Catch the cabinet panel's free edge with the left gripper. + if t < 100: + if x < 0.205: + a[0] = 0.09 + if y < 0.12: + a[1] = 0.1 + if 100 <= t < 240: + a[2] = 0.55 + elif 240 <= t < 320: + a[2] = 0.55 + 0.19 * (t - 240) / 80 + if 100 <= t < 240: + a[5] = -0.3 + elif 240 <= t < 320: + a[5] = -0.3 + 0.5 * (t - 240) / 80 + elif t >= 320: + a[5] = 0.2 + a[19] = 0 if t < 185 or t >= 700 else 1 + if 360 <= t < 670: + a[0] = -0.12 + + # Walk around the panel while leaving it open. + if t >= 700: + a[20] = 0 + if 750 <= t < 980: + drive(a, obs, -0.18, 0.65, 0) + elif 980 <= t < 1190: + drive(a, obs, 0.30, 0.65, 0) + elif 1190 <= t < 1400: + drive(a, obs, 0.32, 0.65, -1.0) + elif 1400 <= t < 1700: + drive(a, obs, 0.45, 0.50, -1.0) + + if t >= 1700 and self.grasp_at is None: + i = min((t - 1700) // 78, len(self.candidates) - 1) + q = (t - 1700) % 78 + h, p, roll, sy, elbow, torso, tx, ty = self.candidates[i] + a[2] = h + a[4] = torso + a[12:16] = [p, roll, sy, elbow] + a[19] = 0 + if q < 30 and h >= 0.73: + drive(a, obs, tx, ty, -1.0, 0.09) + if q >= 35: + a[20] = 1 + a[4] = torso + min(0.14, 0.14 * (q - 35) / 25) + else: + a[20] = 0 + if i >= 2 and q >= 45: + fingers = obs["low_dim_obs"][19:21] + if min(fingers) > -0.018: + im = tools.image("right_wrist") + roi = im[14:66, 27:57].astype(np.float32) + brown = ((roi[..., 0] > 1.12 * roi[..., 1]) & + (roi[..., 1] > 1.10 * roi[..., 2]) & + (roi[..., 0] > 80) & (roi[..., 0] < 230)) + if int(brown.sum()) >= 5: + self.grasp_at = t + + if self.grasp_at is not None: + dt = t - self.grasp_at + a[20] = 1 + a[19] = 0 + if dt < 130: + f = min(1.0, dt / 100) + a[2] = 0.74 + a[4] = 0 + a[12] = -0.55 * f + a[14] = 0.2 * f + a[15] = 0.3 * f + elif dt < 280: + a[12] = -0.55 + a[14] = 0.2 + a[15] = 0.3 + drive(a, obs, 0.24, 0.58, -0.5, 0.09) + elif dt < 440: + a[12] = -0.55 + a[14] = 0.45 + a[15] = 0.3 + a[4] = 0.15 + else: + a[12] = -0.5 + a[14] = 0.45 + a[15] = 0.3 + a[20] = 0 + return a diff --git a/policies/saucepan_to_hob/gpt6sol-s2/episodes.csv b/policies/saucepan_to_hob/gpt6sol-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8bdd4e6043da73ac776c1ce5081f089e7a50e206 --- /dev/null +++ b/policies/saucepan_to_hob/gpt6sol-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4650,timeout,0 +620001,0,4650,timeout,0 +620002,0,4650,timeout,0 +620003,0,4650,timeout,0 +620004,0,4650,timeout,0 +620005,0,4650,timeout,0 +620006,0,4650,timeout,0 +620007,0,4650,timeout,0 +620008,0,4650,timeout,0 +620009,0,4650,timeout,0 +620010,0,4650,timeout,0 +620011,0,4650,timeout,0 +620012,0,4650,timeout,0 +620013,0,4650,timeout,0 +620014,0,4650,timeout,0 +620015,0,4650,timeout,0 +620016,0,4650,timeout,0 +620017,0,4650,timeout,0 +620018,0,4650,timeout,0 +620019,0,4650,timeout,0 +620020,0,4650,timeout,0 +620021,0,4650,timeout,0 +620022,0,4650,timeout,0 +620023,0,4650,timeout,0 +620024,0,4650,timeout,0 +620025,0,4650,timeout,0 +620026,0,4650,timeout,0 +620027,0,4650,timeout,0 +620028,0,4650,timeout,0 +620029,0,4650,timeout,0 +620030,0,4650,timeout,0 +620031,0,4650,timeout,0 +620032,0,4650,timeout,0 +620033,0,4650,timeout,0 +620034,0,4650,timeout,0 +620035,0,4650,timeout,0 +620036,0,4650,timeout,0 +620037,0,4650,timeout,0 +620038,0,4650,timeout,0 +620039,0,4650,timeout,0 +620040,0,4650,timeout,0 +620041,0,4650,timeout,0 +620042,0,4650,timeout,0 +620043,0,4650,timeout,0 +620044,0,4650,timeout,0 +620045,0,4650,timeout,0 +620046,0,4650,timeout,0 +620047,0,4650,timeout,0 +620048,0,4650,timeout,0 +620049,0,4650,timeout,0 +620050,0,4650,timeout,0 +620051,0,4650,timeout,0 +620052,0,4650,timeout,0 +620053,0,4650,timeout,0 +620054,0,4650,timeout,0 +620055,0,4650,timeout,0 +620056,0,4650,timeout,0 +620057,0,4650,timeout,0 +620058,0,4650,timeout,0 +620059,0,4650,timeout,0 +620060,0,4650,timeout,0 +620061,0,4650,timeout,0 +620062,0,4650,timeout,0 +620063,0,4650,timeout,0 +620064,0,4650,timeout,0 +620065,0,4650,timeout,0 +620066,0,4650,timeout,0 +620067,0,4650,timeout,0 +620068,0,4650,timeout,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,0,4650,timeout,0 +620073,0,4650,timeout,0 +620074,0,4650,timeout,0 +620075,0,4650,timeout,0 +620076,0,4650,timeout,0 +620077,0,4650,timeout,0 +620078,0,4650,timeout,0 +620079,0,4650,timeout,0 +620080,0,4650,timeout,0 +620081,0,4650,timeout,0 +620082,0,4650,timeout,0 +620083,0,4650,timeout,0 +620084,0,4650,timeout,0 +620085,0,4650,timeout,0 +620086,0,4650,timeout,0 +620087,0,4650,timeout,0 +620088,0,4650,timeout,0 +620089,0,4650,timeout,0 +620090,0,4650,timeout,0 +620091,0,4650,timeout,0 +620092,0,4650,timeout,0 +620093,0,4650,timeout,0 +620094,0,4650,timeout,0 +620095,0,4650,timeout,0 +620096,0,4650,timeout,0 +620097,0,4650,timeout,0 +620098,0,4650,timeout,0 +620099,0,4650,timeout,0 diff --git a/policies/saucepan_to_hob/gpt6sol-s2/policy.py b/policies/saucepan_to_hob/gpt6sol-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..981dd85bbae10d35919dce6170211393fbfa83af --- /dev/null +++ b/policies/saucepan_to_hob/gpt6sol-s2/policy.py @@ -0,0 +1,125 @@ +"""Deterministic camera-guided manipulation policy for the saucepan task.""" +import math +import cv2 +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.cmd = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.phase = 0 + self.phase_t = 0 + self.pickup = False + self.last_pan = None + self.pan_hits = 0 + self.pick_t = 0 + self.phases = [ + (75, None, .74, 0, (.15, 0, 0, 0, 0, 0, 0), (.15, 0, 0, 0, 0, 0, 0), 0, 0), + (65, None, .74, 0, (.15, 0, 0, 0, 0, 0, 0), (.15, 0, 0, 0, 0, 0, 0), 1, 1), + (150, (-.13, 0, 0), .74, 0, (.8, 0, 0, 0, 0, 0, 0), (.8, 0, 0, 0, 0, 0, 0), 1, 1), + (110, (0, .12, 0), .74, 0, (.8, .35, 0, 0, 0, 0, 0), (.8, 0, 0, 0, 0, 0, 0), 1, 0), + (250, 'home', .74, 0, (0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0), 0, 0), + (100, None, .74, .35, (-.1, .5, 0, 0, 0, .8, 0), (0, 0, 0, 0, 0, 0, 0), 0, 0), + (65, None, .74, .35, (-.1, .5, 0, 0, 0, .8, 0), (0, 0, 0, 0, 0, 0, 0), 1, 0), + (170, (-.13, .08, 0), .74, 0, (.2, .9, 0, 0, 0, .8, 0), (0, 0, 0, 0, 0, 0, 0), 1, 0), + (250, 'home', .74, 0, (0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0), 0, 0), + (110, None, .45, 0, (0, .25, 0, 0, 0, .6, 0), (0, 0, 0, 0, 0, 0, 0), 0, 0), + (70, None, .45, 0, (0, .25, 0, 0, 0, .6, 0), (0, 0, 0, 0, 0, 0, 0), 1, 0), + (180, (-.15, 0, 0), .74, 0, (.5, .65, 0, 0, 0, .6, 0), (0, 0, 0, 0, 0, 0, 0), 1, 0), + ] + + def _pan(self, img): + hsv = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) + mask = cv2.inRange(hsv, (2, 48, 42), (26, 255, 235)) + mask[:18] = 0 + n, labels, stats, centers = cv2.connectedComponentsWithStats(mask) + best = None + best_area = 0 + for i in range(1, n): + x, y, w, h, area = stats[i] + if 11 <= area <= 550 and .45 <= w / max(1, h) <= 2.3 and 18 <= centers[i, 1] <= 68: + if area > best_area: + best = (float(centers[i, 0]), float(centers[i, 1]), math.sqrt(float(area) / math.pi)) + best_area = area + return best + + def _home(self, raw, q): + x, y, _, yaw = q[21:25] + ex, ey = .17 - x, -y + wx = np.clip(1.4 * ex, -.23, .23) if abs(ex) > .028 else 0.0 + wy = np.clip(1.4 * ey, -.23, .23) if abs(ey) > .028 else 0.0 + c, s = math.cos(float(yaw)), math.sin(float(yaw)) + vx, vy = c * wx + s * wy, -s * wx + c * wy + if 0 < abs(vx) < .065: vx = math.copysign(.065, vx) + if 0 < abs(vy) < .065: vy = math.copysign(.065, vy) + raw[0], raw[1] = vx, vy + raw[3] = np.clip(-1.6 * yaw, -.5, .5) if abs(yaw) > .04 else 0 + + def _pickup_action(self, raw, q, tools): + t = self.pick_t + x, y, _, yaw = q[21:25] + if t < 190: + raw[2] = .65 + raw[4] = .15 + raw[5:12] = (0, .3, 0, 0, 0, 0, 0) + raw[12:19] = (.3, -.2, 0, .2, 0, .35, 0) + raw[19:21] = (0, 0) + if self.last_pan is not None: + px, py, radius = self.last_pan + if radius < 9 and x < .21: raw[0] = .09 + if px > 49: raw[1] = -.09 + elif px < 35: raw[1] = .09 + raw[3] = np.clip(-1.4 * yaw, -.35, .35) + elif t < 265: + raw[2] = .65 + raw[4] = .2 + raw[12:19] = (.38, -.1, 0, .3, 0, .4, 0) + raw[19:21] = (0, 1) + elif t < 425: + raw[2] = .74 + raw[4] = 0 + raw[12:19] = (-.6, -.05, 0, .25, 0, .25, 0) + raw[19:21] = (0, 1) + self._home(raw, q) + elif t < 605: + raw[2] = .74 + raw[4] = .1 + raw[12:19] = (-.75, -.02, 0, .25, 0, .4, 0) + raw[19:21] = (0, 1) + self._home(raw, q) + else: + raw[2] = .74 + raw[4] = 0 + raw[12:19] = (-.6, 0, 0, .3, 0, .6, 0) + raw[19:21] = (0, 0) + self.pick_t += 1 + + def act(self, obs, tools): + q = np.asarray(obs['low_dim_obs']) + raw = self.cmd.copy() + raw[0] = raw[1] = raw[3] = 0 + if obs['t'] % 8 == 0: + self.last_pan = self._pan(tools.image('head')) + self.pan_hits = self.pan_hits + 1 if self.last_pan is not None else 0 + if self.pan_hits >= 3: + self.pickup = True + if self.pickup: + self._pickup_action(raw, q, tools) + else: + if self.phase >= len(self.phases): + self.phase = 0 + self.phase_t = 0 + duration, movement, height, torso, left, right, gl, gr = self.phases[self.phase] + raw[2], raw[4] = height, torso + raw[5:12], raw[12:19] = left, right + raw[19:21] = gl, gr + if movement == 'home': + self._home(raw, q) + elif movement is not None: + raw[0], raw[1], raw[3] = movement + self.phase_t += 1 + if self.phase_t >= duration: + self.phase += 1 + self.phase_t = 0 + self.cmd = raw + return raw diff --git a/policies/saucepan_to_hob/gpt6sol-s3/episodes.csv b/policies/saucepan_to_hob/gpt6sol-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8bdd4e6043da73ac776c1ce5081f089e7a50e206 --- /dev/null +++ b/policies/saucepan_to_hob/gpt6sol-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4650,timeout,0 +620001,0,4650,timeout,0 +620002,0,4650,timeout,0 +620003,0,4650,timeout,0 +620004,0,4650,timeout,0 +620005,0,4650,timeout,0 +620006,0,4650,timeout,0 +620007,0,4650,timeout,0 +620008,0,4650,timeout,0 +620009,0,4650,timeout,0 +620010,0,4650,timeout,0 +620011,0,4650,timeout,0 +620012,0,4650,timeout,0 +620013,0,4650,timeout,0 +620014,0,4650,timeout,0 +620015,0,4650,timeout,0 +620016,0,4650,timeout,0 +620017,0,4650,timeout,0 +620018,0,4650,timeout,0 +620019,0,4650,timeout,0 +620020,0,4650,timeout,0 +620021,0,4650,timeout,0 +620022,0,4650,timeout,0 +620023,0,4650,timeout,0 +620024,0,4650,timeout,0 +620025,0,4650,timeout,0 +620026,0,4650,timeout,0 +620027,0,4650,timeout,0 +620028,0,4650,timeout,0 +620029,0,4650,timeout,0 +620030,0,4650,timeout,0 +620031,0,4650,timeout,0 +620032,0,4650,timeout,0 +620033,0,4650,timeout,0 +620034,0,4650,timeout,0 +620035,0,4650,timeout,0 +620036,0,4650,timeout,0 +620037,0,4650,timeout,0 +620038,0,4650,timeout,0 +620039,0,4650,timeout,0 +620040,0,4650,timeout,0 +620041,0,4650,timeout,0 +620042,0,4650,timeout,0 +620043,0,4650,timeout,0 +620044,0,4650,timeout,0 +620045,0,4650,timeout,0 +620046,0,4650,timeout,0 +620047,0,4650,timeout,0 +620048,0,4650,timeout,0 +620049,0,4650,timeout,0 +620050,0,4650,timeout,0 +620051,0,4650,timeout,0 +620052,0,4650,timeout,0 +620053,0,4650,timeout,0 +620054,0,4650,timeout,0 +620055,0,4650,timeout,0 +620056,0,4650,timeout,0 +620057,0,4650,timeout,0 +620058,0,4650,timeout,0 +620059,0,4650,timeout,0 +620060,0,4650,timeout,0 +620061,0,4650,timeout,0 +620062,0,4650,timeout,0 +620063,0,4650,timeout,0 +620064,0,4650,timeout,0 +620065,0,4650,timeout,0 +620066,0,4650,timeout,0 +620067,0,4650,timeout,0 +620068,0,4650,timeout,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,0,4650,timeout,0 +620073,0,4650,timeout,0 +620074,0,4650,timeout,0 +620075,0,4650,timeout,0 +620076,0,4650,timeout,0 +620077,0,4650,timeout,0 +620078,0,4650,timeout,0 +620079,0,4650,timeout,0 +620080,0,4650,timeout,0 +620081,0,4650,timeout,0 +620082,0,4650,timeout,0 +620083,0,4650,timeout,0 +620084,0,4650,timeout,0 +620085,0,4650,timeout,0 +620086,0,4650,timeout,0 +620087,0,4650,timeout,0 +620088,0,4650,timeout,0 +620089,0,4650,timeout,0 +620090,0,4650,timeout,0 +620091,0,4650,timeout,0 +620092,0,4650,timeout,0 +620093,0,4650,timeout,0 +620094,0,4650,timeout,0 +620095,0,4650,timeout,0 +620096,0,4650,timeout,0 +620097,0,4650,timeout,0 +620098,0,4650,timeout,0 +620099,0,4650,timeout,0 diff --git a/policies/saucepan_to_hob/gpt6sol-s3/policy.py b/policies/saucepan_to_hob/gpt6sol-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..31bb6fc9580c2813336059d6c4874f13a5e4f5a8 --- /dev/null +++ b/policies/saucepan_to_hob/gpt6sol-s3/policy.py @@ -0,0 +1,87 @@ +"""Deterministic, hand-written saucepan-to-hob controller. + +The first arm motion hooks the free edge of the cabinet door. The robot then +steps around the open edge before reaching for the saucepan handle. +""" + +import math +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.rest = np.asarray(tools.hold_action(), dtype=np.float32) + + @staticmethod + def _walk_to(a, obs, tx, ty, tyaw): + q = obs["low_dim_obs"] + x, y, yaw = float(q[21]), float(q[22]), float(q[24]) + ex, ey = tx - x, ty - y + wx = max(-0.16, min(0.16, 2.0 * ex)) + wy = max(-0.16, min(0.16, 2.0 * ey)) + vx = wx * math.cos(yaw) + wy * math.sin(yaw) + vy = -wx * math.sin(yaw) + wy * math.cos(yaw) + a[0] = vx if abs(vx) >= 0.055 else 0.0 + a[1] = vy if abs(vy) >= 0.055 else 0.0 + err = math.atan2(math.sin(tyaw - yaw), math.cos(tyaw - yaw)) + a[3] = max(-0.35, min(0.35, 1.5 * err)) if abs(err) > 0.035 else 0.0 + + def act(self, obs, tools): + t = int(obs["t"]) + a = self.rest.copy() + a[0:2] = 0 + a[2] = 0.74 + a[3:5] = 0 + a[5:19] = 0 + a[19:21] = 0 + + # Approach with the left gripper around the free edge of the door. + if t < 241: + a[5] = 0.4 + a[6] = 0.4 if t < 124 else 0.05 + a[7] = 0.2 + a[12] = 1.0 + a[19] = 0.0 if t < 94 else 1.0 + if t < 94: + a[0] = 0.12 + elif t >= 124: + a[0] = -0.12 + return a + + # Walk around the exposed end, keeping both hands clear of the panel. + a[5] = 1.0 + a[6] = 0.05 + a[7] = 0.2 + a[12] = 1.0 + if t < 310: + return a + if t <= 620: + tx = 0.12 if t < 500 else 0.30 + ta = 0.0 if t < 500 else -0.25 + self._walk_to(a, obs, tx, 0.25, ta) + return a + + # Pass the right hand around the open door, then lift toward the + # saucepan handle. Keep the gripper open until the hand is in place. + a[14] = 1.4 + if t >= 690: + a[12] = -0.35 + if t >= 790: + a[14] = 1.0 + if t >= 860: + a[20] = 1.0 + if t >= 930: + a[12] = -0.55 + a[15] = 0.1 + if 1020 <= t < 1150: + self._walk_to(a, obs, 0.14, 0.25, -0.25) + if 1150 <= t < 1250: + self._walk_to(a, obs, 0.28, 0.05, 0.0) + if t >= 1250: + a[4] = 0.15 + a[12] = -0.45 + a[14] = 0.2 + a[15] = 0.15 + if t >= 1370: + a[20] = 0.0 + return a diff --git a/policies/saucepan_to_hob/kimi31pro-s3/episodes.csv b/policies/saucepan_to_hob/kimi31pro-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8bdd4e6043da73ac776c1ce5081f089e7a50e206 --- /dev/null +++ b/policies/saucepan_to_hob/kimi31pro-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4650,timeout,0 +620001,0,4650,timeout,0 +620002,0,4650,timeout,0 +620003,0,4650,timeout,0 +620004,0,4650,timeout,0 +620005,0,4650,timeout,0 +620006,0,4650,timeout,0 +620007,0,4650,timeout,0 +620008,0,4650,timeout,0 +620009,0,4650,timeout,0 +620010,0,4650,timeout,0 +620011,0,4650,timeout,0 +620012,0,4650,timeout,0 +620013,0,4650,timeout,0 +620014,0,4650,timeout,0 +620015,0,4650,timeout,0 +620016,0,4650,timeout,0 +620017,0,4650,timeout,0 +620018,0,4650,timeout,0 +620019,0,4650,timeout,0 +620020,0,4650,timeout,0 +620021,0,4650,timeout,0 +620022,0,4650,timeout,0 +620023,0,4650,timeout,0 +620024,0,4650,timeout,0 +620025,0,4650,timeout,0 +620026,0,4650,timeout,0 +620027,0,4650,timeout,0 +620028,0,4650,timeout,0 +620029,0,4650,timeout,0 +620030,0,4650,timeout,0 +620031,0,4650,timeout,0 +620032,0,4650,timeout,0 +620033,0,4650,timeout,0 +620034,0,4650,timeout,0 +620035,0,4650,timeout,0 +620036,0,4650,timeout,0 +620037,0,4650,timeout,0 +620038,0,4650,timeout,0 +620039,0,4650,timeout,0 +620040,0,4650,timeout,0 +620041,0,4650,timeout,0 +620042,0,4650,timeout,0 +620043,0,4650,timeout,0 +620044,0,4650,timeout,0 +620045,0,4650,timeout,0 +620046,0,4650,timeout,0 +620047,0,4650,timeout,0 +620048,0,4650,timeout,0 +620049,0,4650,timeout,0 +620050,0,4650,timeout,0 +620051,0,4650,timeout,0 +620052,0,4650,timeout,0 +620053,0,4650,timeout,0 +620054,0,4650,timeout,0 +620055,0,4650,timeout,0 +620056,0,4650,timeout,0 +620057,0,4650,timeout,0 +620058,0,4650,timeout,0 +620059,0,4650,timeout,0 +620060,0,4650,timeout,0 +620061,0,4650,timeout,0 +620062,0,4650,timeout,0 +620063,0,4650,timeout,0 +620064,0,4650,timeout,0 +620065,0,4650,timeout,0 +620066,0,4650,timeout,0 +620067,0,4650,timeout,0 +620068,0,4650,timeout,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,0,4650,timeout,0 +620073,0,4650,timeout,0 +620074,0,4650,timeout,0 +620075,0,4650,timeout,0 +620076,0,4650,timeout,0 +620077,0,4650,timeout,0 +620078,0,4650,timeout,0 +620079,0,4650,timeout,0 +620080,0,4650,timeout,0 +620081,0,4650,timeout,0 +620082,0,4650,timeout,0 +620083,0,4650,timeout,0 +620084,0,4650,timeout,0 +620085,0,4650,timeout,0 +620086,0,4650,timeout,0 +620087,0,4650,timeout,0 +620088,0,4650,timeout,0 +620089,0,4650,timeout,0 +620090,0,4650,timeout,0 +620091,0,4650,timeout,0 +620092,0,4650,timeout,0 +620093,0,4650,timeout,0 +620094,0,4650,timeout,0 +620095,0,4650,timeout,0 +620096,0,4650,timeout,0 +620097,0,4650,timeout,0 +620098,0,4650,timeout,0 +620099,0,4650,timeout,0 diff --git a/policies/saucepan_to_hob/kimi31pro-s3/policy.py b/policies/saucepan_to_hob/kimi31pro-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..3391236d28e0090b385d8cd300c87c2f9a7a8e53 --- /dev/null +++ b/policies/saucepan_to_hob/kimi31pro-s3/policy.py @@ -0,0 +1,174 @@ +"""Deterministic hand-written controller for the saucepan task.""" + +import numpy as np + + +class Policy: + def reset(self, obs, tools): + self.cmd = np.asarray(tools.hold_action(), dtype=np.float32).copy() + self.cmd[19:21] = 0.0 + self.phase = "left_approach" + self.phase_t = 0 + self.duration = 80 + self.start = self.cmd.copy() + self.target = self.cmd.copy() + self.target[4] = 0.3 + self.target[5:12] = [-0.4, 0.55, 0.0, 0.5, -0.55, 0.0, 0.0] + self.candidate = 0 + self.grasped = False + # Hand-tuned alternatives cover depth, height and handle approach angle. + self.candidates = [ + (-1.0, 0.6, 0.0, 0.2, 0.0), + (-1.4, 0.6, -0.3, 0.2, 0.2), + (-1.4, 1.0, -0.3, 0.2, 0.3), + (-1.8, 1.0, 0.0, 0.2, 0.5), + (-1.8, 1.2, -0.3, 0.2, 0.6), + (-1.0, 1.4, 0.0, 0.2, 0.0), + (-1.8, 0.6, 0.3, 0.2, 0.5), + (-0.8, 1.2, -0.6, 0.4, 0.1), + ] + + def _go(self, phase, target, duration): + self.phase = phase + self.phase_t = 0 + self.start = self.cmd.copy() + self.target = np.asarray(target, dtype=np.float32).copy() + self.duration = int(duration) + + @staticmethod + def _base_servo(obs, tx, ty, tyaw): + q = obs["low_dim_obs"] + x, y, yaw = float(q[21]), float(q[22]), float(q[24]) + c, s = np.cos(yaw), np.sin(yaw) + ex, ey = tx - x, ty - y + + def speed(v): + if abs(v) < 0.005: + return 0.0 + return float(np.sign(v) * min(0.12, max(0.06, abs(3.5 * v)))) + + return speed(c * ex + s * ey), speed(-s * ex + c * ey), float( + np.clip(3.0 * (tyaw - yaw), -0.2, 0.2) + ) + + def _contact(self, obs): + fingers = obs["low_dim_obs"][19:21] + return bool(np.mean(fingers + 0.02) > 0.0012) + + def _right_target(self, values): + p, e, yaw, roll, wp = values + a = self.cmd.copy() + a[12:19] = [p, roll, yaw, e, -roll, wp, -yaw] + a[20] = 0.0 + return a + + def _begin_lift(self): + a = self.cmd.copy() + a[2] = 0.85 + a[5:12] = 0.0 + a[19] = 0.0 + a[12:19] = [-0.8, 0.2, 0.0, 0.6, -0.2, 0.3, 0.0] + a[20] = 1.0 + self._go("lift", a, 90) + + def act(self, obs, tools): + phase = self.phase + u = min(1.0, (self.phase_t + 1) / max(1, self.duration - 5)) + a = self.start * (1.0 - u) + self.target * u + + if phase == "drawer_open": + a = self.cmd.copy() + k = self.phase_t + a[0] = -0.08 if k < 110 else 0.0 + a[10] = 0.9 * min(1.0, k / 110.0) + elif phase in ("move_hob", "lower_hob", "release_pan", "settle"): + a[0], a[1], a[3] = self._base_servo(obs, 0.12, 0.0, 0.0) + + a = np.asarray(a, dtype=np.float32) + self.cmd = a.copy() + self.phase_t += 1 + + if self.phase_t < self.duration: + return a + + # Phase transitions. Contact is checked only after a commanded closure. + if phase == "left_approach": + t = self.cmd.copy() + t[19] = 1.0 + self._go("left_close", t, 35) + elif phase == "left_close": + self._go("drawer_open", self.cmd, 150) + elif phase == "drawer_open": + t = self.cmd.copy() + t[10] = 0.9 + t[12:19] = [-1.4, 0.2, 0.0, 1.0, -0.2, 0.3, 0.0] + t[20] = 0.0 + self._go("right_clear", t, 70) + elif phase == "right_clear": + t = self.cmd.copy() + # Dark-brown pan segmentation; the bright wood and black hob are excluded. + im = np.asarray(tools.image("right_wrist"), dtype=np.float32) + r, g, b = im[:, :, 0], im[:, :, 1], im[:, :, 2] + mask = (r > 45) & (r < 165) & (r > 1.3 * g) & (g > 1.05 * b) & (b < 110) + ys, xs = np.nonzero(mask) + if len(xs) >= 20: + x, y = float(xs.mean()), float(ys.mean()) + t[14] = np.clip((x - 42.0) * 0.011, -0.6, 0.3) + t[17] = np.clip(0.3 + (y - 55.0) * 0.008, -0.2, 0.8) + t[18] = -t[14] + self._go("align", t, 50) + elif phase == "align": + t = self.cmd.copy() + t[20] = 1.0 + self._go("close", t, 35) + elif phase == "close": + if self._contact(obs): + self.grasped = True + self._begin_lift() + else: + t = self.cmd.copy() + t[20] = 0.0 + self._go("candidate_open", t, 15) + elif phase == "candidate_open": + if self.candidate < len(self.candidates): + t = self._right_target(self.candidates[self.candidate]) + self._go("candidate_approach", t, 45) + else: + self._go("hold", self.cmd, 10**9) + elif phase == "candidate_approach": + t = self.cmd.copy() + t[20] = 1.0 + self._go("candidate_close", t, 25) + elif phase == "candidate_close": + if self._contact(obs): + self.grasped = True + self._begin_lift() + else: + self.candidate += 1 + t = self.cmd.copy() + t[20] = 0.0 + self._go("candidate_open", t, 15) + elif phase == "lift": + t = self.cmd.copy() + t[12:19] = [-1.2, 0.2, 0.0, -0.2, -0.2, 0.5, 0.0] + t[20] = 1.0 + self._go("move_hob", t, 160) + elif phase == "move_hob": + t = self.cmd.copy() + t[2] = 0.74 + t[12:19] = [-0.8, 0.2, 0.0, 0.6, -0.2, 0.3, 0.0] + t[20] = 1.0 + self._go("lower_hob", t, 70) + elif phase == "lower_hob": + t = self.cmd.copy() + t[20] = 0.0 + self._go("release_pan", t, 35) + elif phase == "release_pan": + t = self.cmd.copy() + t[12:19] = [-0.4, 0.2, 0.0, 0.4, -0.2, 0.3, 0.0] + self._go("settle", t, 60) + elif phase == "settle": + self._go("hold", self.cmd, 10**9) + else: + self._go("hold", self.cmd, 10**9) + return self.cmd.copy() diff --git a/policies/saucepan_to_hob/opus-s1/episodes.csv b/policies/saucepan_to_hob/opus-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..2294405ab43edbd89ede94bc0f5640431849e697 --- /dev/null +++ b/policies/saucepan_to_hob/opus-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4650,timeout,0 +620001,0,4650,timeout,0 +620002,0,4650,timeout,0 +620003,0,4650,timeout,0 +620004,0,4650,timeout,0 +620005,0,4650,timeout,0 +620006,0,4650,timeout,0 +620007,0,4650,timeout,0 +620008,0,4650,timeout,0 +620009,0,4650,timeout,0 +620010,0,4650,timeout,0 +620011,0,4650,timeout,0 +620012,0,4650,timeout,0 +620013,0,4650,timeout,0 +620014,0,4650,timeout,0 +620015,0,4650,timeout,0 +620016,0,4650,timeout,0 +620017,0,4650,timeout,0 +620018,0,4650,timeout,0 +620019,0,4650,timeout,0 +620020,0,4650,timeout,0 +620021,0,4650,timeout,0 +620022,0,4650,timeout,0 +620023,0,4650,timeout,0 +620024,0,4650,timeout,0 +620025,0,4650,timeout,0 +620026,0,4650,timeout,0 +620027,0,4650,timeout,0 +620028,0,4650,timeout,0 +620029,0,4650,timeout,0 +620030,0,4650,timeout,0 +620031,0,4650,timeout,0 +620032,0,4650,timeout,0 +620033,0,4650,timeout,0 +620034,0,4650,timeout,0 +620035,0,4650,timeout,0 +620036,0,4650,timeout,0 +620037,0,4650,timeout,0 +620038,0,4650,timeout,0 +620039,0,4650,timeout,0 +620040,0,4650,timeout,0 +620041,0,4650,timeout,0 +620042,0,4650,timeout,0 +620043,0,4650,timeout,0 +620044,0,4650,timeout,0 +620045,0,4650,timeout,0 +620046,0,4650,timeout,0 +620047,0,4650,timeout,0 +620048,0,4650,timeout,0 +620049,0,4650,timeout,0 +620050,0,4650,timeout,0 +620051,0,4650,timeout,0 +620052,0,4650,timeout,0 +620053,0,4650,timeout,0 +620054,0,4650,timeout,0 +620055,0,4650,timeout,0 +620056,0,4650,timeout,0 +620057,0,4650,timeout,0 +620058,0,4650,timeout,0 +620059,0,4650,timeout,0 +620060,0,4650,timeout,0 +620061,0,4650,timeout,0 +620062,0,4650,timeout,0 +620063,0,4650,timeout,0 +620064,0,4650,timeout,0 +620065,0,4650,timeout,0 +620066,0,4650,timeout,0 +620067,0,3511,fell,1 +620068,0,4650,timeout,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,0,4650,timeout,0 +620073,0,4650,timeout,0 +620074,0,4650,timeout,0 +620075,0,4650,timeout,0 +620076,0,4650,timeout,0 +620077,0,4650,timeout,0 +620078,0,4650,timeout,0 +620079,0,4650,timeout,0 +620080,0,4650,timeout,0 +620081,0,4650,timeout,0 +620082,0,4650,timeout,0 +620083,0,4650,timeout,0 +620084,0,4650,timeout,0 +620085,0,4650,timeout,0 +620086,0,4650,timeout,0 +620087,0,4650,timeout,0 +620088,0,4650,timeout,0 +620089,0,4650,timeout,0 +620090,0,4650,timeout,0 +620091,0,4650,timeout,0 +620092,0,4650,timeout,0 +620093,0,4650,timeout,0 +620094,0,4650,timeout,0 +620095,0,4650,timeout,0 +620096,0,4650,timeout,0 +620097,0,4650,timeout,0 +620098,0,4650,timeout,0 +620099,0,4650,timeout,0 diff --git a/policies/saucepan_to_hob/opus-s1/g1fk.py b/policies/saucepan_to_hob/opus-s1/g1fk.py new file mode 100644 index 0000000000000000000000000000000000000000..444c9e0990a680da2d28bcfff4a7a140fb470121 --- /dev/null +++ b/policies/saucepan_to_hob/opus-s1/g1fk.py @@ -0,0 +1,79 @@ +"""Forward kinematics of the G1 arms (from the published g1_29dof URDF geometry).""" +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, p): + T = np.eye(4) + T[:3, :3] = R + T[:3, 3] = p + return T + + +AX = {'x': _rx, 'y': _ry, 'z': _rz} + + +def chain(side): + s = 1.0 if side == 'L' else -1.0 + return [ + # (xyz, rpy, axis) + ((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'), + ] + + +_CH = {'L': chain('L'), 'R': chain('R')} + + +def torso_T(waist): + """pelvis -> torso_link, waist = (yaw, roll, pitch).""" + T = _T(_rz(waist[0]), np.zeros(3)) + T = T @ _T(np.eye(3), np.array([-0.0039635, 0, 0.035])) @ _T(_rx(waist[1]), np.zeros(3)) + T = T @ _T(np.eye(3), np.array([0, 0, 0.019])) @ _T(_ry(waist[2]), np.zeros(3)) + return T + + +def arm_T(side, q, tool=0.0): + """torso_link -> wrist_yaw_link frame (+ tool offset along local x).""" + T = np.eye(4) + for (xyz, rpy, ax), qi in zip(_CH[side], q): + T = T @ _T(_rpy(*rpy), np.array(xyz)) @ _T(AX[ax](qi), np.zeros(3)) + if tool: + T = T @ _T(np.eye(3), np.array([tool, 0, 0])) + return T + + +def hand_in_pelvis(side, q, waist, tool=0.0): + return torso_T(waist) @ arm_T(side, q, tool) + + +def hand_world(obs_vec, side, q=None, tool=0.0): + x = obs_vec + waist = x[0:3] + if q is None: + q = x[3:10] if side == 'L' else x[12:19] + Tp = _T(_rz(x[24]), np.array([x[21], x[22], x[23]])) + return Tp @ hand_in_pelvis(side, q, waist, tool) diff --git a/policies/saucepan_to_hob/opus-s1/g1ik.py b/policies/saucepan_to_hob/opus-s1/g1ik.py new file mode 100644 index 0000000000000000000000000000000000000000..2ad96d3632bf57e67be510e362b426a6e6afc0eb --- /dev/null +++ b/policies/saucepan_to_hob/opus-s1/g1ik.py @@ -0,0 +1,39 @@ +"""Numerical IK for the G1 arms on top of g1fk.""" +import numpy as np +from scipy.optimize import least_squares + +from g1fk import hand_in_pelvis + +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': # roll and yaw limits mirror + lo[1], hi[1] = -HI[1], -LO[1] + return lo, hi + + +def ik(side, target, waist, q0, xdir=None, zdir=None, tool=0.12, w_ori=0.3, w_reg=0.02, q_ref=None): + """Solve joints so the tool point (wrist_yaw frame + tool along x) reaches target (pelvis frame). + + xdir: desired direction of the hand x axis (pointing direction); zdir: desired hand z axis. + """ + lo, hi = limits(side) + q0 = np.clip(np.asarray(q0, float), lo + 1e-3, hi - 1e-3) + qr = q0 if q_ref is None else np.asarray(q_ref, float) + + def res(q): + T = hand_in_pelvis(side, q, waist, tool) + r = [T[:3, 3] - target] + if xdir is not None: + r.append(w_ori * (T[:3, 0] - xdir)) + if zdir is not None: + r.append(w_ori * (T[:3, 2] - zdir)) + r.append(w_reg * (q - qr)) + return np.concatenate(r) + + sol = least_squares(res, q0, bounds=(lo, hi), xtol=1e-8, ftol=1e-8, max_nfev=200) + T = hand_in_pelvis(side, sol.x, waist, tool) + return sol.x, np.linalg.norm(T[:3, 3] - target) diff --git a/policies/saucepan_to_hob/opus-s1/headcam.py b/policies/saucepan_to_hob/opus-s1/headcam.py new file mode 100644 index 0000000000000000000000000000000000000000..877d098e143910292e65cbbe044adf6c6999e23f --- /dev/null +++ b/policies/saucepan_to_hob/opus-s1/headcam.py @@ -0,0 +1,49 @@ +"""Head camera model (fitted offline against the arm kinematics) and pixel <-> world helpers.""" +import numpy as np + +from g1fk import _rx, _ry, _rz, _T, torso_T + +# camera position in torso frame, roll/pitch/yaw, focal (px at 84x84) +CAM = np.array([0.0827, 0.0063, 0.4145, -0.06, 1.1112, -0.0404, 76.6267]) + + +def cam_R(): + return _rz(CAM[5]) @ _ry(CAM[4]) @ _rx(CAM[3]) + + +def pelvis_world(x, beta=0.0): + """Pelvis pose in world; beta = pelvis pitch (not observed, estimated).""" + return _T(_rz(x[24]) @ _ry(beta), np.array([x[21], x[22], x[23]])) + + +def torso_world(x, beta=0.0): + return pelvis_world(x, beta) @ torso_T(x[0:3]) + + +def cam_world(x, beta=0.0): + Tt = torso_world(x, beta) + Tc = _T(cam_R(), CAM[0:3]) + return Tt @ Tc + + +def project(x, P, beta=0.0): + """World point -> (u, v) pixel (84x84 image), and depth.""" + T = cam_world(x, beta) + pc = T[:3, :3].T @ (np.asarray(P, float) - T[:3, 3]) + f = CAM[6] + return np.array([42 - f * pc[1] / pc[0], 42 - f * pc[2] / pc[0]]), pc[0] + + +def ray(x, u, v, beta=0.0): + """Pixel -> (origin, unit direction) in world.""" + T = cam_world(x, beta) + f = CAM[6] + d = np.array([1.0, -(u - 42) / f, -(v - 42) / f]) + d = T[:3, :3] @ d + return T[:3, 3], d / np.linalg.norm(d) + + +def pixel_on_plane_z(x, u, v, z, beta=0.0): + o, d = ray(x, u, v, beta) + t = (z - o[2]) / d[2] + return o + t * d diff --git a/policies/saucepan_to_hob/opus-s1/planner.py b/policies/saucepan_to_hob/opus-s1/planner.py new file mode 100644 index 0000000000000000000000000000000000000000..1abd48a0fd718cac5adca9419caad1c9cb1b29fd --- /dev/null +++ b/policies/saucepan_to_hob/opus-s1/planner.py @@ -0,0 +1,55 @@ +"""Offline-style IK planner: choose a base position from which a grasp pose is reachable without the +arm touching the counter edge.""" +import numpy as np + +from g1fk import AX, _CH, _T, _rpy, torso_T +from g1ik import ik + + +def link_points(side, q, waist): + T = torso_T(waist) + pts = [] + for (xyz, rpy, ax), qi in zip(_CH[side], q): + T = T @ _T(_rpy(*rpy), np.array(xyz)) @ _T(AX[ax](qi), np.zeros(3)) + pts.append(T[:3, 3].copy()) + return np.array(pts) + + +Q0S = [np.zeros(7), np.array([-1.0, -0.2, 0.5, 0.5, 0, 0, 0]), np.array([-1.2, 0.1, -0.5, 1.0, 1.0, 0, -1.2]), + np.array([-1.0, 0.3, 0.5, 1.0, -1.0, 0, 1.2])] + + +def solve_at(side, G, X, Z, base, pz, wp, tool=0.13): + t = G - np.array([base[0], base[1], pz]) + best = None + for q0 in Q0S: + q0 = q0.copy() + if side == 'L': + q0[[1, 2, 4, 6]] *= -1 + q, e = ik(side, t, np.array([0, 0, wp]), q0, xdir=X, zdir=Z, tool=tool, w_ori=0.5) + if best is None or e < best[1]: + best = (q, e) + q, e = best + W = link_points(side, q, np.array([0, 0, wp])) + np.array([base[0], base[1], pz]) + return q, e, W + + +def clearance_ok(W, x_front=0.57, z_top=0.78): + for P in W[3:]: # elbow and beyond + if P[0] > x_front and P[2] > z_top: + return False + return True + + +def plan_base(side, G, X, Z, pz, wp, xs, ys, tool=0.13): + best = None + for bx in xs: + for by in ys: + q, e, W = solve_at(side, G, X, Z, (bx, by), pz, wp, tool) + if e > 0.01 or not clearance_ok(W): + continue + # prefer the base far from the cabinet and with the elbow low + score = -bx + 0.5 * abs(by - G[1]) * 0 + if best is None or score < best[0]: + best = (score, bx, by, e) + return best diff --git a/policies/saucepan_to_hob/opus-s1/policy.py b/policies/saucepan_to_hob/opus-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..54862db092eaf453712330084c61f583801215d3 --- /dev/null +++ b/policies/saucepan_to_hob/opus-s1/policy.py @@ -0,0 +1,73 @@ +"""Saucepan-to-hob policy for the simulated Unitree G1. + +Hand-written, scripted control: + 1. walk up to the cabinet, grab the door handle with the left hand and pull the door open while + the base follows the handle's arc (one re-grasp if the handle slips); + 2. walk around the open door to the front-left of the cabinet; + 3. find the saucepan in the head camera (colour segmentation, back-projection onto the shelf + plane with a head-camera model calibrated against the arm kinematics); + 4. squat, bring the right hand in horizontally and close it on the handle (a few heights tried); + 5. lift, carry the pan out under the counter edge, stand up, raise it over the hob, lower it until + contact, open the hand and retract. + +The script is a generator of raw actions (see skills.py / skills2.py next to this file). +""" + +import numpy as np + +import skills +import skills2 + + +def _script(c): + yield from skills2.open_door(c) + attempts = 0 + while attempts < 2 and c.obs['t'] < 3300: + attempts += 1 + if attempts > 1: + # stand up and step back out before re-looking + yield from skills.hold(c, 10, rg=0.0) + yield from skills.joint_move(c, 'R', skills2.R_J1, n=30) + yield from skills.joint_move(c, 'R', skills.R_DOWN, n=30) + for k in range(1, 61): + yield from skills.hold(c, 1, h=0.52 + (0.74 - 0.52) * k / 60, p=0.3 * (1 - k / 60)) + c.beta = 0.0 + yield from skills.goto(c, 0.07, 0.20, 0.0, tol=0.04, maxn=200) + yield from skills.hold(c, 20, p=0.0) + pan = None + try: + pan = skills2.locate_pan(c) + except Exception: + pan = None + if pan is None or not (0.6 < pan['center'][0] < 0.85 and -0.15 < pan['center'][1] < 0.3): + pan = {'center': np.array([0.70, 0.10, 0.5]), 'dir': np.array([0.0, -1.0])} + res = yield from skills2.grasp_handle_fwd(c, pan, s=0.085, z_list=(0.585, 0.60, 0.565)) + if res[3]: + yield from skills2.lift45(c, res[0], res[1], res[2], z1=0.62, z_high=1.08, z_min=0.93) + break + while True: + yield c.act(vx=0.0, vy=0.0, wz=0.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.float32) + self.c = skills.Ctx(obs, tools, self.hold) + self.c.corr = {'L': np.zeros(3), 'R': np.zeros(3)} + self.c.beta = 0.0 + self.gen = _script(self.c) + self.failed = False + + def act(self, obs, tools): + self.c.obs = obs + if not self.failed: + try: + a = next(self.gen) + return np.asarray(a, dtype=np.float32) + except Exception: + self.failed = True + a = self.c.a.copy() + a[0] = a[1] = a[3] = 0.0 + return a diff --git a/policies/saucepan_to_hob/opus-s1/skills.py b/policies/saucepan_to_hob/opus-s1/skills.py new file mode 100644 index 0000000000000000000000000000000000000000..6afc5f56c01718371a0d2f732f75e247eea7f170 --- /dev/null +++ b/policies/saucepan_to_hob/opus-s1/skills.py @@ -0,0 +1,269 @@ +"""Blocking-style skills written as generators that yield raw actions.""" +import numpy as np + +from g1fk import hand_world +from g1ik import ik + +L_DOWN = np.array([0.0, 0.1, 0.0, 1.5, 0, 0, 0]) +R_DOWN = np.array([0.0, -0.1, 0.0, 1.5, 0, 0, 0]) + +# door geometry (world frame, fixed across seeds) +HINGE = np.array([0.62, -0.31]) +RAD = 0.59 +ZH = 0.655 +HOFF = -0.025 + + +class Ctx: + def __init__(self, obs, tools, hold): + self.obs = obs + self.tools = tools + self.a = np.asarray(hold, dtype=np.float32).copy() + self.log = [] + + @property + def x(self): + return self.obs['low_dim_obs'] + + def act(self, **kw): + a = self.a.copy() + names = dict(vx=0, vy=1, h=2, wz=3, p=4, lg=19, rg=20) + for k, v in kw.items(): + if k in names: + a[names[k]] = v + elif k == 'L': + a[5:12] = v + elif k == 'R': + a[12:19] = v + return a + + +def run(c, a, n): + c.a = np.asarray(a, dtype=np.float32).copy() + for _ in range(n): + yield c.a + + +def hold(c, n, **kw): + yield from run(c, c.act(**kw), n) + + +def _Ry(b): + cb, sb = np.cos(b), np.sin(b) + return np.array([[cb, 0, sb], [0, 1, 0], [-sb, 0, cb]]) + + +def w2p(c, P): + x = c.x + cs, sn = np.cos(x[24]), np.sin(x[24]) + d = np.asarray(P, float) - x[21:24] + v = np.array([cs * d[0] + sn * d[1], -sn * d[0] + cs * d[1], d[2]]) + return _Ry(getattr(c, 'beta', 0.0)).T @ v + + +def dw2p(c, D): + x = c.x + cs, sn = np.cos(x[24]), np.sin(x[24]) + v = np.array([cs * D[0] + sn * D[1], -sn * D[0] + cs * D[1], D[2]]) + return _Ry(getattr(c, 'beta', 0.0)).T @ v + + +def solve(c, side, Pw, X=None, Z=None, tool=0.13, w_ori=0.5, q0=None): + idx = slice(3, 10) if side == 'L' else slice(12, 19) + q0 = c.x[idx].copy() if q0 is None else q0 + q, err = ik(side, w2p(c, Pw), c.x[0:3], q0, + xdir=None if X is None else dw2p(c, X), + zdir=None if Z is None else dw2p(c, Z), tool=tool, w_ori=w_ori) + return q, err + + +Q0S = [np.zeros(7), np.array([-1.0, -0.2, 0.5, 0.5, 0, 0, 0]), np.array([-1.2, 0.1, -0.5, 1.0, 1.0, 0, -1.2]), + np.array([-1.0, 0.3, 0.5, 1.0, -1.0, 0, 1.2]), np.array([-0.6, 0.2, -0.6, 0.35, 1.1, 0.3, -0.8])] + + +def solve_multi(c, side, Pw, X=None, Z=None, tool=0.13, w_ori=0.5): + """IK from several seeds; returns the best solution (low error, then low elbow).""" + from g1fk import hand_in_pelvis + best = None + for q0 in Q0S: + q0 = q0.copy() + if side == 'L': + q0[[1, 2, 4, 6]] *= -1 + q, e = solve(c, side, Pw, X, Z, tool=tool, w_ori=w_ori, q0=q0) + el = hand_in_pelvis(side, np.r_[q[:4], 0, 0, 0], c.x[0:3], 0.0)[2, 3] + score = e + 0.02 * el + if best is None or score < best[0]: + best = (score, q, e) + return best[1], best[2] + + +def joint_move(c, side, q1, n=40, **kw): + idx = slice(3, 10) if side == 'L' else slice(12, 19) + a0 = c.a[5:12].copy() if side == 'L' else c.a[12:19].copy() + for k in range(1, n + 1): + q = a0 + (np.asarray(q1) - a0) * k / n + kw2 = dict(kw) + kw2[side] = q + yield from run(c, c.act(**kw2), 1) + + +def reach(c, side, Pw, X=None, Z=None, n=30, tool=0.13, w_ori=0.5, **kw): + q, err = solve(c, side, Pw, X, Z, tool, w_ori) + kw[side] = q + yield from run(c, c.act(**kw), n) + return err + + +def hand_pos(c, side, tool=0.13): + x = c.x + v = hand_world(x, side, tool=tool)[:3, 3] - x[21:24] + # hand_world ignores pelvis pitch: rotate the pelvis-relative offset by beta about the yawed y axis + cs, sn = np.cos(x[24]), np.sin(x[24]) + b = np.array([cs * v[0] + sn * v[1], -sn * v[0] + cs * v[1], v[2]]) + b = _Ry(getattr(c, 'beta', 0.0)) @ b + return x[21:24] + np.array([cs * b[0] - sn * b[1], sn * b[0] + cs * b[1], b[2]]) + + +CORR = {'L': np.zeros(3), 'R': np.zeros(3)} + + +def cmove(c, side, P1, X=None, Z=None, steps=40, w_ori=0.5, tool=0.13, settle=10, track=True, ki=0.08, cmax=0.07, **kw): + """Cartesian straight-line move of the tool point (IK re-solved every step). + + With track=True an integral term compensates the steady sag of the position-controlled arm. + """ + idx = slice(3, 10) if side == 'L' else slice(12, 19) + P0 = hand_pos(c, side, tool) + if not hasattr(c, 'corr'): + c.corr = {'L': np.zeros(3), 'R': np.zeros(3)} + q = c.x[idx].copy() + e = 0.0 + P1 = np.asarray(P1, float) + for k in range(1, steps + settle + 1): + P = P0 + (P1 - P0) * min(k, steps) / steps + if track: + err = P - hand_pos(c, side, tool) + c.corr[side] = np.clip(c.corr[side] + ki * err, -cmax, cmax) + q, e = solve(c, side, P + c.corr[side], X, Z, tool=tool, w_ori=w_ori, q0=q) + kw2 = dict(kw) + kw2[side] = q + yield from run(c, c.act(**kw2), 1) + return e + + +def hand_dirs(yaw, ang): + X = np.array([np.cos(yaw) * np.cos(ang), np.sin(yaw) * np.cos(ang), -np.sin(ang)]) + Z = np.array([np.cos(yaw) * np.sin(ang), np.sin(yaw) * np.sin(ang), np.cos(ang)]) + return X, Z + + +def base_cmd(c, xt, yt, yawt, kp=2.0, vmax=0.3, vmin=0.06): + x, y, z, yaw = c.x[21:25] + dx, dy = xt - x, yt - y + cs, sn = np.cos(yaw), np.sin(yaw) + bx, by = cs * dx + sn * dy, -sn * dx + cs * dy + dyaw = (yawt - yaw + np.pi) % (2 * np.pi) - np.pi + vx, vy = np.clip(kp * bx, -vmax, vmax), np.clip(kp * by, -vmax, vmax) + if np.hypot(vx, vy) < vmin: + vx = vy = 0.0 + wz = np.clip(2.0 * dyaw, -0.5, 0.5) + if abs(wz) < 0.06: + wz = 0.0 + return vx, vy, wz, np.hypot(bx, by), dyaw + + +def goto(c, xt, yt, yawt, tol=0.03, maxn=300, vmax=0.25, settle=25, vmin=0.08, **kw): + """Walk to a world pose; the measured pelvis sways while stepping, so it is low-pass filtered.""" + f = c.x[21:23].copy() + for i in range(maxn): + f = 0.9 * f + 0.1 * c.x[21:23] + x, y = f + yaw = c.x[24] + dx, dy = xt - x, yt - y + cs, sn = np.cos(yaw), np.sin(yaw) + bx, by = cs * dx + sn * dy, -sn * dx + cs * dy + dyaw = (yawt - yaw + np.pi) % (2 * np.pi) - np.pi + dist = np.hypot(bx, by) + if dist < tol and abs(dyaw) < 0.04: + break + if dist >= tol: + sp = np.clip(1.0 * dist, vmin, vmax) + vx, vy = bx / dist * sp, by / dist * sp + else: + vx = vy = 0.0 + wz = np.clip(1.5 * dyaw, -0.4, 0.4) + if abs(wz) < 0.08 and abs(dyaw) > 0.04: + wz = 0.08 * np.sign(dyaw) + yield from run(c, c.act(vx=vx, vy=vy, wz=wz, **kw), 1) + yield from run(c, c.act(vx=0, vy=0, wz=0, **kw), settle) + c.log.append(('goto', (xt, yt, yawt), c.x[21:25].copy(), i)) + + +# ---------------------------------------------------------------- door +def door_pt(th, s=RAD, off=0.0): + return np.array([HINGE[0] - s * np.sin(th) + off * np.cos(th), + HINGE[1] + s * np.cos(th) + off * np.sin(th)]) + + +def handle_pt(th): + return np.r_[door_pt(th, RAD, HOFF), ZH] + + +def door_angle_from(P): + d = P[:2] - HINGE + return np.arctan2(-d[0], d[1]) + + +def grab_handle(c): + yield from hold(c, 50, p=0.1, h=0.68) + H = handle_pt(0.0) + X, Z = hand_dirs(0.0, 0.3) + yield from reach(c, 'L', H + [-0.10, 0, 0], X, Z, n=40, lg=0.0) + yield from reach(c, 'L', H + [0.01, 0, 0], X, Z, n=35, lg=0.0) + yield from hold(c, 25, lg=1.0) + c.log.append(('grab', float(c.x[50]))) + + +def base_for(th, fx=0.33, fy=0.22, kpsi=1.0): + h = handle_pt(th) + psi = kpsi * th + cs, sn = np.cos(psi), np.sin(psi) + return np.array([h[0] - fx * cs + fy * sn, h[1] - fx * sn - fy * cs]), psi + + +def pull_door(c, th_end_deg=105, rate_deg=0.12, ang=0.3, h=0.68, p=0.1, kpsi=1.0, regrasps=3): + """Pull by the handle while the base follows; re-grasps the handle when the grip slips.""" + th = 0.0 + q = c.x[3:10].copy() + th_end = np.radians(th_end_deg) + lead = np.radians(5.0) + est = 0.0 + for attempt in range(regrasps + 1): + for _ in range(1300): + if th >= th_end: + break + th = min(th + np.radians(rate_deg), th_end) + bt, psi = base_for(th, kpsi=kpsi) + vx, vy, wz, _, _ = base_cmd(c, bt[0], bt[1], psi) + X, Z = hand_dirs(th, ang) + q, err = solve(c, 'L', handle_pt(th), X, Z, q0=q) + yield from run(c, c.act(L=q, vx=vx, vy=vy, wz=wz, h=h, p=p), 1) + if c.x[50] > 0.95: + break + est = door_angle_from(hand_pos(c, 'L')) + c.log.append(('pull_end', attempt, np.degrees(th), np.degrees(est))) + if th >= th_end or attempt == regrasps: + break + # re-grasp: open, back off along the door normal, come back onto the handle + th = est + X, Z = hand_dirs(th, ang) + nrm = np.r_[np.cos(th), np.sin(th), 0.0] + yield from hold(c, 10, lg=0.0, vx=0, vy=0, wz=0) + yield from cmove(c, 'L', handle_pt(th) - 0.08 * nrm, X, Z, steps=20, track=False) + bt, psi = base_for(th, kpsi=kpsi) + yield from goto(c, bt[0], bt[1], psi, maxn=100, settle=10, h=h, p=p) + yield from cmove(c, 'L', handle_pt(th) - 0.08 * nrm, X, Z, steps=10, track=False) + yield from cmove(c, 'L', handle_pt(th) + 0.01 * nrm, X, Z, steps=20, track=False) + yield from hold(c, 20, lg=1.0) + q = c.x[3:10].copy() + return est diff --git a/policies/saucepan_to_hob/opus-s1/skills2.py b/policies/saucepan_to_hob/opus-s1/skills2.py new file mode 100644 index 0000000000000000000000000000000000000000..8629abae9979789dd0fc7a69563f4f487ebfd753 --- /dev/null +++ b/policies/saucepan_to_hob/opus-s1/skills2.py @@ -0,0 +1,611 @@ +"""Task phases built on skills.py.""" +import cv2 +import numpy as np + +import headcam +from skills import (L_DOWN, R_DOWN, RAD, cmove, door_pt, goto, grab_handle, hand_dirs, hand_pos, hold, + pull_door, reach, run, solve, base_cmd, door_angle_from) + + +def retract_left(c): + yield from hold(c, 10, lg=0.0) + P = hand_pos(c, 'L') + yield from reach(c, 'L', P + np.array([-0.08, -0.08, 0.05]), n=20, w_ori=0.0) + yield from hold(c, 30, L=L_DOWN, h=0.74, p=0.0) + + +def hook_sweep(c, th0, th1, s=0.50, z=0.60, side='L'): + X, Z = hand_dirs(0.0, 0.5) + for P in [door_pt(th0, s=s, off=0.10), door_pt(th0, s=s, off=0.06)]: + yield from reach(c, side, np.r_[P, z], X, None, n=35, w_ori=0.3) + for th in np.arange(th0, th1 + 1e-6, np.radians(2)): + P = np.r_[door_pt(th, s=s, off=0.02), z] + yield from reach(c, side, P, X, None, n=12, w_ori=0.3) + + +def front_push(c, th0, th1=1.85, s=0.35, z=0.70, y0=0.15, y1=0.0, bx=0.12): + """From the cabinet front, push the door's inner face open with the right hand while + the base sidesteps to the right.""" + X = np.array([1.0, 0, 0]) + Z = np.array([0, 0, 1.0]) + P = np.r_[door_pt(th0, s=s, off=0.12), z] + yield from cmove(c, 'R', np.array([bx + 0.25, y0 - 0.15, z]), X, Z, steps=30, w_ori=0.3, track=False) + yield from cmove(c, 'R', P, X, Z, steps=30, w_ori=0.3, track=False) + n = 0 + th = th0 + while th < th1: + th += np.radians(0.25) + frac = (th - th0) / max(th1 - th0, 1e-3) + yt = y0 + (y1 - y0) * frac + vx, vy, wz, _, _ = base_cmd(c, bx, yt, 0.0) + P = np.r_[door_pt(th, s=s, off=0.05), z] + yield from cmove(c, 'R', P, X, Z, steps=1, settle=0, w_ori=0.3, track=False, vx=vx, vy=vy, wz=wz) + n += 1 + yield from hold(c, 20, vx=0, vy=0, wz=0) + c.log.append(('push_end', np.degrees(door_angle_from(np.r_[hand_pos(c, 'R')[:2]])), c.x[21:25].copy())) + P = hand_pos(c, 'R') + yield from cmove(c, 'R', P + np.array([0.0, 0.10, 0.0]), X, Z, steps=20, w_ori=0.3, track=False) + yield from cmove(c, 'R', pel(c, (0.25, -0.15, -0.05)), X, Z, steps=20, w_ori=0.3, track=False) + yield from hold(c, 30, R=R_DOWN) + + +def front_push2(c, th0, th1=np.radians(92), s=0.45, z=0.70, bx=0.05, y0=0.25, y1=0.15, rate=0.2): + """Standing front-left of the cabinet, push the door's inner face with the right hand.""" + X = np.array([1.0, 0, 0]) + Z = np.array([0, 0, 1.0]) + yield from goto(c, bx, y0, 0.0) + c.corr = getattr(c, 'corr', {'L': np.zeros(3), 'R': np.zeros(3)}) + c.corr['R'] = np.zeros(3) + yield from cmove(c, 'R', pel(c, (0.10, -0.20, -0.20)), None, None, steps=25, w_ori=0.0, track=False) + yield from cmove(c, 'R', np.r_[door_pt(th0, s=s, off=0.14), z], X, Z, steps=30, w_ori=0.3, track=False) + th = th0 + while th < th1: + th += np.radians(rate) + frac = (th - th0) / max(th1 - th0, 1e-3) + vx, vy, wz, _, _ = base_cmd(c, bx, y0 + (y1 - y0) * frac, 0.0) + P = np.r_[door_pt(th, s=s, off=0.05), z] + yield from cmove(c, 'R', P, X, Z, steps=1, settle=0, w_ori=0.3, track=False, vx=vx, vy=vy, wz=wz) + yield from hold(c, 20, vx=0, vy=0, wz=0) + c.log.append(('push_end', np.degrees(door_angle_from(hand_pos(c, 'R'))), c.x[21:25].copy())) + P = hand_pos(c, 'R') + yield from cmove(c, 'R', P + np.array([-0.02, 0.10, 0.0]), X, Z, steps=20, w_ori=0.3, track=False) + yield from cmove(c, 'R', pel(c, (0.15, -0.18, -0.15)), None, None, steps=20, w_ori=0.0, track=False) + yield from hold(c, 30, R=R_DOWN) + + +def open_door(c): + yield from hold(c, 20, L=L_DOWN, R=R_DOWN, rg=0.0, lg=0.0) + yield from goto(c, 0.27, 0.0, 0.0) + yield from grab_handle(c) + th = yield from pull_door(c, th_end_deg=100, rate_deg=0.10, regrasps=1) + yield from walk_around(c) + return th + + +def walk_around(c): + yield from retract_left(c) + yield from goto(c, c.x[21] - 0.1, c.x[22], 0.0, maxn=150) + yield from goto(c, -0.30, -0.55, 0.0) + yield from goto(c, -0.30, 0.20, 0.0, tol=0.04, maxn=220) + yield from goto(c, 0.07, 0.20, 0.0, tol=0.04, maxn=220) + yield from hold(c, 30, p=0.0) + + +R_TUCK = np.array([0.58, -0.356, -0.158, -0.156, 0.019, -0.421, 0.097]) + + +def grasp_frame(pan): + """Grasp point on the handle and hand axes for a 45-degree forward-down grasp.""" + d = pan['dir'] + G = np.r_[pan['center'][:2] + 0.14 * d, 0.52] + n = np.array([-d[1], d[0]]) + if n[0] < 0: + n = -n + X = np.r_[0.707 * n, -0.707] + Z = np.r_[d, 0.0] # hand z along the handle (sign fixed below) + if Z[1] > 0: + Z = -Z + return G, X, Z + + +def pel(c, d): + x = c.x + cs, sn = np.cos(x[24]), np.sin(x[24]) + return x[21:24] + np.array([cs * d[0] - sn * d[1], sn * d[0] + cs * d[1], d[2]]) + + +DOWN_X = np.array([0, 0, -1.0]) +DOWN_Z = np.array([0, -1.0, 0]) +RIM_R = 0.07 + + +def handle_grasp(c, pan, s=0.11, bx=0.43, by=0.15, h=0.57, p=0.4, z_grip=0.525, side='L'): + """Top-down grasp of the handle (fingers close across the handle).""" + d = pan['dir'] + G = np.r_[pan['center'][:2] + s * d, z_grip] + Z = np.r_[d, 0.0] + sg = 1.0 if side == 'L' else -1.0 + gk = 'lg' if side == 'L' else 'rg' + yield from hold(c, 20, R=R_DOWN, L=L_DOWN, rg=0.0, lg=0.0, h=0.74, p=0.0) + yield from goto(c, bx, by, 0.0) + yield from hold(c, 60, h=h, p=p) + c.log.append(('squat', c.x[21:25].copy(), c.x[0:3].copy())) + yield from cmove(c, side, pel(c, (0.05, sg * 0.25, 0.0)), None, None, steps=25, w_ori=0.0) + yield from cmove(c, side, pel(c, (0.17, sg * 0.12, 0.17)), DOWN_X, Z, steps=30, w_ori=0.3) + yield from cmove(c, side, G + np.array([0, 0, 0.10]), DOWN_X, Z, steps=30) + c.log.append(('pre_handle', hand_pos(c, side), G, c.x[21:25].copy())) + yield from cmove(c, side, G, DOWN_X, Z, steps=25) + yield from hold(c, 30, **{gk: 1.0}) + c.log.append(('handle_grip', float(c.x[50 if side == 'L' else 51]), hand_pos(c, side), c.x[21:25].copy())) + return G + + +def servo_hold(c, side, P, X, Z, n, **kw): + """Keep the tool point at a world target for n steps while other commands act.""" + yield from cmove(c, side, P, X, Z, steps=1, settle=n - 1, **kw) + + +def approach_grasp(c, pan, s=0.10, bx=0.41, by=0.05, h=0.57, p=0.4, z_grip=0.525, z_in=0.575, side='L'): + """Walk in with arms down, raise the arm outside the cabinet, squat with the hand servoed, + slide the hand in above the handle and grasp it from above.""" + d = pan['dir'] + G = np.r_[pan['center'][:2] + s * d, z_grip] + Z = np.r_[d, 0.0] + gk = 'lg' if side == 'L' else 'rg' + sg = 1.0 if side == 'L' else -1.0 + yield from hold(c, 20, R=R_DOWN, L=L_DOWN, rg=0.0, lg=0.0, h=0.74, p=0.0) + yield from goto(c, bx, by, 0.0) + c.log.append(('at_cab', c.x[21:25].copy())) + yield from cmove(c, side, pel(c, (0.05, sg * 0.25, -0.1)), None, None, steps=25, w_ori=0.0) + yield from cmove(c, side, pel(c, (0.12, sg * 0.18, 0.08)), None, None, steps=25, w_ori=0.0) + P = np.array([0.53, G[1], 0.62]) + yield from cmove(c, side, P, DOWN_X, Z, steps=30, w_ori=0.3) + c.log.append(('raised', c.x[21:25].copy(), hand_pos(c, side))) + yield from servo_hold(c, side, P, DOWN_X, Z, 70, h=h, p=p) + c.log.append(('squat', c.x[21:25].copy(), c.x[0:3].copy(), hand_pos(c, side))) + yield from cmove(c, side, np.array([0.53, G[1], z_in]), DOWN_X, Z, steps=20) + yield from cmove(c, side, np.array([G[0], G[1], z_in]), DOWN_X, Z, steps=30) + c.log.append(('pre_handle', hand_pos(c, side), G, c.x[21:25].copy())) + yield from cmove(c, side, G, DOWN_X, Z, steps=25) + yield from hold(c, 30, **{gk: 1.0}) + c.log.append(('handle_grip', float(c.x[50 if side == 'L' else 51]), hand_pos(c, side), c.x[21:25].copy())) + return G + + +def rim_grasp2(c, pan, side='L', bx=0.38, by=0.03, h=0.6, p=0.4, z_grip=0.515, z_in=0.565, tries=3): + """Pinch the pan's front wall from above; the wrist stays under the counter edge.""" + C = pan['center'] + sg = 1.0 if side == 'L' else -1.0 + gk = 'lg' if side == 'L' else 'rg' + gi = 50 if side == 'L' else 51 + yield from hold(c, 20, R=R_DOWN, L=L_DOWN, rg=0.0, lg=0.0, h=0.74, p=0.0) + yield from goto(c, bx, C[1] + by, 0.0) + yield from hold(c, 60, h=h, p=p) + c.log.append(('squat', c.x[21:25].copy(), c.x[0:3].copy())) + yield from cmove(c, side, pel(c, (0.05, sg * 0.25, -0.05)), None, None, steps=25, w_ori=0.0) + yield from cmove(c, side, pel(c, (0.12, sg * 0.18, 0.10)), None, None, steps=25, w_ori=0.0) + yield from cmove(c, side, np.array([0.50, C[1], 0.62]), DOWN_X, DOWN_Z, steps=30, w_ori=0.3) + yield from cmove(c, side, np.array([0.50, C[1], z_in]), DOWN_X, DOWN_Z, steps=15) + c.log.append(('raised', c.x[21:25].copy(), hand_pos(c, side))) + wall = C[0] - RIM_R + for k in range(tries): + x = wall + 0.025 * k + yield from cmove(c, side, np.array([x, C[1], z_in]), DOWN_X, DOWN_Z, steps=20, **{gk: 0.0}) + yield from cmove(c, side, np.array([x, C[1], z_grip]), DOWN_X, DOWN_Z, steps=15) + yield from hold(c, 25, **{gk: 1.0}) + g = float(c.x[gi]) + c.log.append(('pinch', k, g, hand_pos(c, side), c.x[21:25].copy())) + if g < 0.95: + return True + yield from hold(c, 10, **{gk: 0.0}) + yield from cmove(c, side, np.array([x, C[1], z_in]), DOWN_X, DOWN_Z, steps=10) + return False + + +def grasp_handle_planned(c, pan, s=0.09, xbias=0.055, h=0.57, p=0.4, pz=0.55, wp=0.24, z_grip=0.525, z_in=0.57): + from planner import solve_at, clearance_ok + d = pan.get('dir', np.array([0.0, -1.0])) + if d[1] > -0.75: # the handle always points to the robot's right; reject bad fits + d = np.array([0.0, -1.0]) + Cc = pan['center'][:2] + np.array([xbias, 0.0]) + G = np.r_[Cc + s * d, z_grip] + n = np.array([-d[1], d[0]]) + if n[0] < 0: + n = -n + choice = None + for a in [np.radians(70), np.radians(55), np.radians(45)]: + X = np.r_[np.cos(a) * n, -np.sin(a)] + Y = np.cross(np.r_[d, 0.0], X) + Z = np.cross(X, Y) + for dy in [0.14, 0.17, 0.20, 0.11]: + for bx in [0.30, 0.32, 0.34]: + base = (bx, max(G[1] + dy, 0.17)) + q, e, W = solve_at('R', G, X, Z, base, pz, wp) + q2, e2, W2 = solve_at('R', np.array([G[0], G[1], z_in]), X, Z, base, pz, wp) + if e < 0.008 and e2 < 0.008 and clearance_ok(W) and clearance_ok(W2): + choice = base + break + if choice: + break + if choice: + break + c.log.append(('plan', G, choice, np.degrees(a))) + if choice is None: + choice = (0.36, max(G[1] + 0.08, 0.07)) + c.corr = {'L': np.zeros(3), 'R': np.zeros(3)} + yield from hold(c, 20, R=R_DOWN, L=L_DOWN, rg=0.0, lg=0.0, h=0.74, p=0.0) + yield from goto(c, choice[0] + 0.035, choice[1], 0.0) + yield from hold(c, 60, h=h, p=p) + c.log.append(('squat', c.x[21:25].copy(), c.x[0:3].copy())) + yield from cmove(c, 'R', pel(c, (0.05, -0.25, -0.05)), None, None, steps=25, w_ori=0.0, track=False) + yield from cmove(c, 'R', pel(c, (0.12, -0.18, 0.10)), None, None, steps=25, w_ori=0.0, track=False) + xb = 0.52 - 0.21 * np.cos(a) + yield from cmove(c, 'R', np.array([xb, G[1], 0.62]), X, Z, steps=30, w_ori=0.3) + yield from cmove(c, 'R', np.array([xb, G[1], z_in]), X, Z, steps=15) + yield from cmove(c, 'R', np.array([G[0], G[1], z_in]), X, Z, steps=30) + c.log.append(('above', hand_pos(c, 'R'), G, c.corr['R'].copy(), c.x[21:25].copy())) + ok, Gf = yield from descend_and_grip(c, G, X, Z, z_in) + return Gf, X, Z, ok + + +def grasp_rim_planned(c, pan, xbias=0.055, h=0.57, p=0.4, pz=0.55, wp=0.24, z_grip=0.53, z_in=0.60, + a_list=(55, 45, 70)): + """Pinch the pan's front wall (tilted top-down approach) with the right hand.""" + from planner import solve_at, clearance_ok + Cc = pan['center'][:2] + np.array([xbias, 0.0]) + G = np.array([Cc[0] - RIM_R, Cc[1], z_grip]) + choice = None + for a in [np.radians(v) for v in a_list]: + X = np.array([np.cos(a), 0, -np.sin(a)]) + Y = np.array([np.sin(a), 0, np.cos(a)]) + Z = np.cross(X, Y) + for dy in [0.15, 0.18, 0.12]: + for bx in [0.30, 0.32, 0.34]: + base = (bx, max(G[1] + dy, 0.17)) + q, e, W = solve_at('R', G, X, Z, base, pz, wp) + q2, e2, W2 = solve_at('R', np.array([G[0] + 0.04, G[1], z_in]), X, Z, base, pz, wp) + if e < 0.008 and e2 < 0.008 and clearance_ok(W) and clearance_ok(W2): + choice = base + break + if choice: + break + if choice: + break + c.log.append(('plan_rim', G, choice, np.degrees(a))) + if choice is None: + choice = (0.34, max(G[1] + 0.15, 0.17)) + c.corr = {'L': np.zeros(3), 'R': np.zeros(3)} + yield from hold(c, 20, R=R_DOWN, L=L_DOWN, rg=0.0, lg=0.0, h=0.74, p=0.0) + yield from goto(c, choice[0] + 0.035, choice[1], 0.0, tol=0.04, maxn=220) + yield from hold(c, 60, h=h, p=p) + c.log.append(('squat', c.x[21:25].copy(), c.x[0:3].copy())) + yield from raise_right(c, np.array([0.50, G[1], z_in]), X, Z) + c.log.append(('front', hand_pos(c, 'R'), G, c.corr['R'].copy(), c.x[21:25].copy())) + ok, Gf = yield from descend_and_grip(c, G, X, Z, z_in, offsets=(0.0, 0.025, -0.02, 0.045)) + return Gf, X, Z, ok + + +R_J1 = np.array([0.0, -0.45, 0.0, 0.3, 0.0, 0.0, 0.0]) + + +def beta_for(h): + """Estimated (unobserved) forward pelvis pitch in a squat commanded with torso pitch 0.2.""" + return 0.27 * float(np.clip((0.6 - h) / 0.15, 0.0, 1.0)) + + +R_OUT = np.array([0.0, -0.7, 0.0, 1.3, 0.0, 0.0, 0.0]) +R_MID = np.array([-0.8, -0.6, 0.0, 0.6, 0.0, 0.0, 0.0]) + + +def lift_from_deep(c, G, X, Z, x1=0.55, z1=0.63, x2=0.44, z2=0.74, z_high=1.0, x_place=0.72, z_min=0.86): + """Carry the pinched pan out of the cabinet while rising from the deep squat, then place it.""" + yield from cmove(c, 'R', np.array([G[0], G[1], z1]), X, Z, steps=30, settle=10) + c.log.append(('lifted', hand_pos(c, 'R'), float(c.x[51]))) + yield from cmove(c, 'R', np.array([x1, G[1], z1]), X, Z, steps=40, settle=10) + P = np.array([x1, G[1], z1]) + for k in range(1, 81): + hh = 0.45 + (0.62 - 0.45) * k / 80 + c.beta = beta_for(hh) + yield from cmove(c, 'R', P, X, Z, steps=1, settle=0, h=hh, p=0.2 + 0.2 * k / 80) + yield from cmove(c, 'R', np.array([x2, G[1], z1]), X, Z, steps=30, settle=10) + yield from cmove(c, 'R', np.array([x2, G[1], z2]), X, Z, steps=30, settle=10) + c.log.append(('out', hand_pos(c, 'R'), float(c.x[51]), c.x[21:25].copy())) + yield from lift_and_place_tail(c, G, X, Z, x2, z2, z_high, x_place, z_min, h0=0.62, p0=0.4) + + +def lift_and_place_tail(c, G, X, Z, x_out, z_out, z_high, x_place, z_min, h0, p0): + P = np.array([x_out, G[1], z_out]) + for k in range(1, 81): + hh = h0 + (0.74 - h0) * k / 80 + c.beta = beta_for(hh) + yield from cmove(c, 'R', P, X, Z, steps=1, settle=0, h=hh, p=p0 * (1 - k / 80)) + yield from cmove(c, 'R', np.array([x_out, G[1], z_high]), X, Z, steps=40, settle=10) + c.log.append(('high', hand_pos(c, 'R'), float(c.x[51]), c.x[21:25].copy())) + yield from cmove(c, 'R', np.array([x_place, G[1], z_high]), X, Z, steps=50, settle=10) + z = z_high + while z > z_min: + z -= 0.002 + yield from cmove(c, 'R', np.array([x_place, G[1], z]), X, Z, steps=1, settle=0, track=False) + if z < hand_pos(c, 'R')[2] - 0.02: + break + yield from hold(c, 20) + c.log.append(('placed', hand_pos(c, 'R'), z, c.x[21:25].copy())) + yield from hold(c, 30, rg=0.0) + P = hand_pos(c, 'R') + yield from cmove(c, 'R', P + np.array([-0.05, 0, 0.08]), None, None, steps=30, w_ori=0.0, track=False) + yield from cmove(c, 'R', pel(c, (0.2, -0.2, 0.0)), None, None, steps=30, w_ori=0.0, track=False) + yield from hold(c, 40, R=R_DOWN) + + +def grasp_handle45(c, pan, s=0.09, xbias=0.055, a=45, standx=0.375, z_grip=0.53, z_in=0.66): + """Squat (h 0.57), approach above the handle root from the front and grasp it (fingers across).""" + d = pan.get('dir', np.array([0.0, -1.0])) + if d[1] > -0.75: + d = np.array([0.0, -1.0]) + Cc = pan['center'][:2] + np.array([xbias, 0.0]) + G = np.r_[Cc + s * d, z_grip] + n = np.array([-d[1], d[0]]) + if n[0] < 0: + n = -n + ar = np.radians(a) + X = np.r_[np.cos(ar) * n, -np.sin(ar)] + Y = np.cross(np.r_[d, 0.0], X) + Z = np.cross(X, Y) + by = max(G[1] + 0.15, 0.17) + c.corr = {'L': np.zeros(3), 'R': np.zeros(3)} + c.beta = 0.0 + yield from hold(c, 20, R=R_DOWN, L=L_DOWN, rg=0.0, lg=0.0, h=0.74, p=0.0) + yield from goto(c, standx, by, 0.0, tol=0.04, maxn=220) + for k in range(1, 61): + yield from hold(c, 1, h=0.74 + (0.57 - 0.74) * k / 60, p=0.4 * k / 60) + yield from hold(c, 30) + c.log.append(('squat', c.x[21:25].copy(), c.x[0:3].copy())) + yield from raise_right(c, np.array([0.55, G[1], z_in]), X, Z) + c.log.append(('front', hand_pos(c, 'R'), G, c.corr['R'].copy(), c.x[21:25].copy())) + ok, Gf = yield from descend_and_grip(c, G, X, Z, z_in, offsets=(0.0, 0.03, -0.03, 0.06)) + return Gf, X, Z, ok + + +def grasp_handle_fwd(c, pan, s=0.12, xbias=0.03, standx=0.395, z_list=(0.555, 0.585, 0.53), hs=0.52, ps=0.3): + """Squat, bring the hand horizontally (fingers above/below) onto the handle from the front.""" + d = pan.get('dir', np.array([0.0, -1.0])) + if d[1] > -0.75: + d = np.array([0.0, -1.0]) + Cc = pan['center'][:2] + np.array([xbias, 0.0]) + G0 = Cc + s * d + X = np.array([1.0, 0, 0]) + Z = np.array([0, -1.0, 0]) + by = max(G0[1] + 0.15, 0.17) + c.corr = {'L': np.zeros(3), 'R': np.zeros(3)} + c.beta = 0.0 + yield from hold(c, 20, R=R_DOWN, L=L_DOWN, rg=0.0, lg=0.0, h=0.74, p=0.0) + yield from goto(c, standx, by, 0.0, tol=0.04, maxn=220) + for k in range(1, 81): + yield from hold(c, 1, h=0.74 + (hs - 0.74) * k / 80, p=ps * k / 80) + yield from hold(c, 30) + c.beta = max(0.0, (ps - c.x[2]) * 1.2 - 0.05) + c.log.append(('squat', c.x[21:25].copy(), c.x[0:3].copy(), c.beta)) + yield from raise_right(c, np.array([0.50, G0[1], z_list[0]]), X, Z) + c.log.append(('front', hand_pos(c, 'R'), G0, c.corr['R'].copy(), c.x[21:25].copy())) + for z in z_list: + yield from cmove(c, 'R', np.array([0.50, G0[1], z]), X, Z, steps=15, settle=10, rg=0.0) + yield from cmove(c, 'R', np.array([G0[0] - 0.08, G0[1], z]), X, Z, steps=25, settle=10) + yield from cmove(c, 'R', np.array([G0[0] + 0.01, G0[1], z]), X, Z, steps=30, settle=15) + yield from hold(c, 25, rg=1.0) + g = float(c.x[51]) + c.log.append(('fwd_try', z, hand_pos(c, 'R'), g, c.x[21:25].copy())) + if g < 0.95: + return np.r_[G0, z], X, Z, True + yield from hold(c, 10, rg=0.0) + return np.r_[G0, z_list[0]], X, Z, False + + +def lift45(c, G, X, Z, x_hold=0.60, z1=0.62, x_out=0.47, z_out=0.75, z_high=1.0, x_place=0.72, z_min=0.86, + h0=0.52, p0=0.3): + yield from cmove(c, 'R', np.array([G[0], G[1], z1]), X, Z, steps=50, settle=10) + c.log.append(('lifted', hand_pos(c, 'R'), float(c.x[51]))) + yield from cmove(c, 'R', np.array([x_hold, G[1], z1]), X, Z, steps=80, settle=10) + P = np.array([x_hold, G[1], z1]) + b0 = getattr(c, 'beta', 0.0) + for k in range(1, 81): + c.beta = b0 * (1 - k / 80) + yield from cmove(c, 'R', P, X, Z, steps=1, settle=0, h=h0 + (0.74 - h0) * k / 80, p=p0 * (1 - k / 80)) + yield from cmove(c, 'R', np.array([x_out, G[1], z1]), X, Z, steps=30, settle=10) + yield from cmove(c, 'R', np.array([x_out, G[1], z_out]), X, Z, steps=30, settle=10) + c.log.append(('out', hand_pos(c, 'R'), float(c.x[51]), c.x[21:25].copy())) + yield from lift_and_place_tail(c, G, X, Z, x_out, z_out, z_high, x_place, z_min, h0=0.74, p0=0.0) + + +def deep_grasp2(c, pan, xbias=0.055, z_grip=0.53, z_in=0.61, a=55, standx=0.37, x_stage=0.66): + """Deep squat with the arms down, raise the right arm around the knee, pinch the pan's front wall.""" + from skills import joint_move, solve_multi + Cc = pan['center'][:2] + np.array([xbias, 0.0]) + G = np.array([Cc[0] - RIM_R, Cc[1], z_grip]) + ar = np.radians(a) + X = np.array([np.cos(ar), 0, -np.sin(ar)]) + Y = np.array([np.sin(ar), 0, np.cos(ar)]) + Z = np.cross(X, Y) + by = max(G[1] + 0.13, 0.17) + c.corr = {'L': np.zeros(3), 'R': np.zeros(3)} + c.beta = 0.0 + yield from hold(c, 20, R=R_DOWN, L=L_DOWN, rg=0.0, lg=0.0, h=0.74, p=0.0) + yield from goto(c, standx, by, 0.0, tol=0.04, maxn=220) + for k in range(1, 101): + yield from hold(c, 1, h=0.74 + (0.45 - 0.74) * k / 100, p=0.2 * k / 100) + yield from hold(c, 30) + c.beta = beta_for(0.45) + c.log.append(('deep', c.x[21:25].copy(), c.x[0:3].copy())) + yield from joint_move(c, 'R', R_OUT, n=30) + yield from joint_move(c, 'R', R_MID, n=40) + S = np.array([min(x_stage, G[0] - 0.01), G[1], z_in]) + q, e = solve_multi(c, 'R', S, X, Z) + c.log.append(('stage_ik', e)) + yield from joint_move(c, 'R', q, n=40) + yield from cmove(c, 'R', S, X, Z, steps=10, settle=15) + c.log.append(('stage', hand_pos(c, 'R'), S, c.corr['R'].copy(), c.x[21:25].copy())) + ok, Gf = yield from descend_and_grip(c, G, X, Z, z_in, offsets=(0.0, 0.025, -0.02, 0.045)) + return Gf, X, Z, ok + + +def deep_grasp(c, pan, xbias=0.055, z_grip=0.53, z_in=0.60, a=55, standx=0.37): + """Deep squat (shoulder below the counter) and pinch the front wall of the pan.""" + from skills import joint_move, solve_multi + Cc = pan['center'][:2] + np.array([xbias, 0.0]) + G = np.array([Cc[0] - RIM_R, Cc[1], z_grip]) + ar = np.radians(a) + X = np.array([np.cos(ar), 0, -np.sin(ar)]) + Y = np.array([np.sin(ar), 0, np.cos(ar)]) + Z = np.cross(X, Y) + by = max(G[1] + 0.13, 0.17) + c.corr = {'L': np.zeros(3), 'R': np.zeros(3)} + c.beta = 0.0 + yield from hold(c, 20, R=R_DOWN, L=L_DOWN, rg=0.0, lg=0.0, h=0.74, p=0.0) + yield from goto(c, standx, by, 0.0, tol=0.04, maxn=220) + P0 = np.array([0.53, G[1], 0.74]) + yield from joint_move(c, 'R', R_J1, n=30) + q, e = solve_multi(c, 'R', P0, X, Z) + yield from joint_move(c, 'R', q, n=40) + yield from cmove(c, 'R', P0, X, Z, steps=10, settle=10) + c.log.append(('ready', hand_pos(c, 'R'), c.x[21:25].copy())) + # squat while the hand keeps its place + for k in range(1, 81): + hh = 0.74 + (0.45 - 0.74) * k / 80 + c.beta = beta_for(hh) + yield from cmove(c, 'R', P0, X, Z, steps=1, settle=0, h=hh, p=0.2 * k / 80) + yield from cmove(c, 'R', P0, X, Z, steps=1, settle=30) + c.log.append(('deep', hand_pos(c, 'R'), c.x[21:25].copy(), c.x[0:3].copy())) + yield from cmove(c, 'R', np.array([0.53, G[1], z_in]), X, Z, steps=25, settle=10) + c.log.append(('front', hand_pos(c, 'R'), G, c.corr['R'].copy(), c.x[21:25].copy())) + ok, Gf = yield from descend_and_grip(c, G, X, Z, z_in, offsets=(0.0, 0.025, -0.02, 0.045)) + return Gf, X, Z, ok + + +def raise_right(c, P, X, Z): + """Bring the right hand from hanging to a point in front of the cabinet, elbow kept low.""" + from skills import joint_move, solve_multi + yield from joint_move(c, 'R', R_J1, n=40) + q, e = solve_multi(c, 'R', P, X, Z) + yield from joint_move(c, 'R', q, n=50) + yield from cmove(c, 'R', P, X, Z, steps=10, settle=10) + + +def descend_and_grip(c, G, X, Z, z_in, offsets=(0.0, 0.035, -0.035, 0.065)): + """Lower the open gripper onto the handle; if the fingers land on the handle, shift and retry.""" + n = np.r_[X[:2], 0.0] + n /= np.linalg.norm(n) + for off in offsets: + Gt = G + off * n + yield from cmove(c, 'R', np.array([Gt[0], Gt[1], z_in]), X, Z, steps=12, settle=5, rg=0.0) + yield from cmove(c, 'R', Gt, X, Z, steps=15, settle=15) + hz = hand_pos(c, 'R')[2] + stalled = hz > Gt[2] + 0.015 + c.log.append(('try', off, hand_pos(c, 'R'), stalled)) + if stalled: + continue + yield from hold(c, 25, rg=1.0) + g = float(c.x[51]) + c.log.append(('grip', g)) + if g < 0.95: + return True, Gt + yield from hold(c, 10, rg=0.0) + return False, G + + +def lift_and_place(c, G, X, Z, x_out=0.47, z_low=0.575, z_high=1.0, x_place=0.72, z_min=0.86, h0=0.45, p0=0.2): + """Carry the pan out of the cabinet, stand up, put it on the hob and let go.""" + yield from cmove(c, 'R', np.array([G[0], G[1], z_low]), X, Z, steps=25, settle=10) + c.log.append(('lifted', hand_pos(c, 'R'), float(c.x[51]))) + yield from cmove(c, 'R', np.array([x_out, G[1], z_low]), X, Z, steps=40, settle=10) + yield from cmove(c, 'R', np.array([x_out, G[1], 0.72]), X, Z, steps=30, settle=10) + c.log.append(('out', hand_pos(c, 'R'), float(c.x[51]), c.x[21:25].copy())) + P = hand_pos(c, 'R') + # stand up while keeping the pan where it is + for k in range(1, 81): + hh = h0 + (0.74 - h0) * k / 80 + pp = p0 * (1 - k / 80) + c.beta = beta_for(hh) + yield from cmove(c, 'R', P, X, Z, steps=1, settle=0, h=hh, p=pp) + yield from cmove(c, 'R', np.array([x_out, G[1], z_high]), X, Z, steps=40, settle=10) + c.log.append(('high', hand_pos(c, 'R'), float(c.x[51]), c.x[21:25].copy())) + yield from cmove(c, 'R', np.array([x_place, G[1], z_high]), X, Z, steps=50, settle=10) + # lower slowly (integrator frozen) until the hand stops following (contact) or z_min + z = z_high + while z > z_min: + z -= 0.002 + yield from cmove(c, 'R', np.array([x_place, G[1], z]), X, Z, steps=1, settle=0, track=False) + if z < hand_pos(c, 'R')[2] - 0.02: + break + yield from hold(c, 20) + c.log.append(('placed', hand_pos(c, 'R'), z, c.x[21:25].copy())) + yield from hold(c, 30, rg=0.0) + P = hand_pos(c, 'R') + yield from cmove(c, 'R', P + np.array([-0.05, 0, 0.08]), None, None, steps=30, w_ori=0.0, track=False) + yield from cmove(c, 'R', pel(c, (0.2, -0.2, 0.0)), None, None, steps=30, w_ori=0.0, track=False) + yield from hold(c, 40, R=R_DOWN) + + +def rim_grasp(c, pan, bx=0.38, by=0.10, h=0.6, p=0.4, z_grip=0.515, xoff=0.0): + """Pinch the front wall of the pan from above with the right hand.""" + C = pan['center'] + G = np.array([C[0] - RIM_R + xoff, C[1], z_grip]) + yield from hold(c, 20, R=R_DOWN, L=L_DOWN, rg=0.0, h=0.74, p=0.0) + yield from goto(c, bx, C[1] + by - 0.06, 0.0) + yield from hold(c, 60, h=h, p=p) + c.log.append(('squat', c.x[21:25].copy(), c.x[0:3].copy())) + # raise the hand in front of the body, then over the rim, then down + yield from cmove(c, 'R', pel(c, (0.05, -0.25, 0.0)), None, None, steps=25, w_ori=0.0) + yield from cmove(c, 'R', pel(c, (0.15, -0.15, 0.15)), DOWN_X, DOWN_Z, steps=30, w_ori=0.3) + yield from cmove(c, 'R', G + np.array([0, 0, 0.10]), DOWN_X, DOWN_Z, steps=30) + c.log.append(('pre_rim', hand_pos(c, 'R'), G)) + yield from cmove(c, 'R', G, DOWN_X, DOWN_Z, steps=25) + yield from hold(c, 30, rg=1.0) + c.log.append(('rim_grip', float(c.x[51]), hand_pos(c, 'R'))) + return G + + +# ---------------------------------------------------------------- pan perception +def pan_masks(im): + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(int) + H, S, V = hsv[..., 0], hsv[..., 1], hsv[..., 2] + body = (H <= 13) & (S > 90) & (V > 25) & (V < 230) + r, b = im[..., 0].astype(int), im[..., 2].astype(int) + handle = (r - b >= 6) & (V > 100) & ~body & (H <= 30) + return body, handle + + +def locate_pan(c, z_body=0.50, z_handle=0.52): + """From a standing pose: pan centre and handle points in world (z planes assumed).""" + import scipy.ndimage as ndi + im = c.tools.image('head') + body, handle = pan_masks(im) + lab, n = ndi.label(body) + if n == 0: + return None + sizes = ndi.sum(body, lab, range(1, n + 1)) + k = int(np.argmax(sizes)) + 1 + vs, us = np.nonzero(lab == k) + cu, cv = us.mean() + 0.5, vs.mean() + 0.5 + C = headcam.pixel_on_plane_z(c.x, cu, cv, z_body) + near = ndi.binary_dilation(lab == k, iterations=3) + hl, hn = ndi.label(handle, structure=np.ones((3, 3))) + keep = np.zeros_like(handle) + for j in range(1, hn + 1): + comp = hl == j + if (comp & near).any(): + keep |= comp + hv, hu = np.nonzero(keep) + pts = np.array([headcam.pixel_on_plane_z(c.x, u + 0.5, v + 0.5, z_handle) for u, v in zip(hu, hv)]) + if len(pts) >= 3: + # keep handle pixels within 0.35 m of the pan centre + dd = np.linalg.norm(pts[:, :2] - C[:2], axis=1) + pts = pts[(dd > 0.05) & (dd < 0.35)] + res = dict(center=C, n_body=int(sizes[k - 1]), handle_pts=pts, cuv=(cu, cv)) + if len(pts) >= 3: + d = pts[:, :2] - C[:2] + dirv = d.mean(axis=0) + dirv /= np.linalg.norm(dirv) + proj = d @ dirv + res['dir'] = dirv + res['tip_dist'] = float(proj.max()) + res['root_dist'] = float(proj.min()) + return res diff --git a/policies/saucepan_to_hob/opus-s2/cam.py b/policies/saucepan_to_hob/opus-s2/cam.py new file mode 100644 index 0000000000000000000000000000000000000000..87f58c3ecdfd8e18e4efe6b1fe7953c7a9fc0d4a --- /dev/null +++ b/policies/saucepan_to_hob/opus-s2/cam.py @@ -0,0 +1,47 @@ +"""Head camera model (G1 d435 mount, URDF constants refined against the gripper +seen in the head image) and pixel <-> ray helpers.""" +import numpy as np +from kin import torso_frame, _ry + +CAM_POS = np.array([0.0576235, 0.01753, 0.42987]) # in the torso frame +CAM_PITCH = 0.8307767 +FOVY = np.deg2rad(58.0) +U_OFF = 0.0 # pixel offset of the principal point +W = H = 84 + + +def cam_pose(waist, cam_pos=CAM_POS, cam_pitch=CAM_PITCH): + """Camera position and axes (fwd, left, up) in the pelvis frame.""" + p, R = torso_frame(waist) + Rc = R @ _ry(cam_pitch) + return p + R @ cam_pos, Rc + + +def pixel_ray(u, v, waist, fovy=FOVY, u_off=U_OFF, **kw): + """Unit ray (pelvis frame) through pixel (u right, v down), image 84x84.""" + pc, Rc = cam_pose(waist, **kw) + f = (H / 2) / np.tan(fovy / 2) + d = np.array([f, -(u - u_off - (W - 1) / 2), -(v - (H - 1) / 2)]) + d = Rc @ d + return pc, d / np.linalg.norm(d) + + +def project(p, waist, fovy=FOVY, u_off=U_OFF, **kw): + """Pelvis-frame point -> pixel (u, v).""" + pc, Rc = cam_pose(waist, **kw) + c = Rc.T @ (np.asarray(p) - pc) + f = (H / 2) / np.tan(fovy / 2) + return (W - 1) / 2 - f * c[1] / c[0] + u_off, (H - 1) / 2 - f * c[2] / c[0] + + +def ray_plane_z(u, v, waist, z, **kw): + """Intersect a pixel ray with the horizontal plane at pelvis-frame height z.""" + pc, d = pixel_ray(u, v, waist, **kw) + t = (z - pc[2]) / d[2] + return pc + t * d + + +def ray_plane_x(u, v, waist, x, **kw): + pc, d = pixel_ray(u, v, waist, **kw) + t = (x - pc[0]) / d[0] + return pc + t * d diff --git a/policies/saucepan_to_hob/opus-s2/episodes.csv b/policies/saucepan_to_hob/opus-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..cc5db10108f37bb48e83fd9aa8320ef96cd40b60 --- /dev/null +++ b/policies/saucepan_to_hob/opus-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4650,timeout,0 +620001,0,4650,timeout,0 +620002,0,4650,timeout,0 +620003,0,4650,timeout,0 +620004,1,3666,success,0 +620005,0,4650,timeout,0 +620006,0,4650,timeout,0 +620007,0,4650,timeout,0 +620008,0,4650,timeout,0 +620009,1,3771,success,0 +620010,0,4650,timeout,0 +620011,1,3709,success,0 +620012,0,4650,timeout,0 +620013,1,3774,success,0 +620014,0,4650,timeout,0 +620015,0,4650,timeout,0 +620016,0,4650,timeout,0 +620017,0,4650,timeout,0 +620018,0,4650,timeout,0 +620019,0,4650,timeout,0 +620020,0,4650,timeout,0 +620021,0,4650,timeout,0 +620022,0,4650,timeout,0 +620023,0,4650,timeout,0 +620024,1,3458,success,0 +620025,1,3739,success,0 +620026,1,3835,success,0 +620027,0,4650,timeout,0 +620028,0,4650,timeout,0 +620029,0,4650,timeout,0 +620030,0,4650,timeout,0 +620031,0,4650,timeout,0 +620032,0,4650,timeout,0 +620033,1,3720,success,0 +620034,0,4650,timeout,0 +620035,0,4650,timeout,0 +620036,0,4650,timeout,0 +620037,0,4650,timeout,0 +620038,0,4650,fell,1 +620039,0,4650,timeout,0 +620040,0,4650,timeout,0 +620041,0,4650,timeout,0 +620042,1,3722,success,0 +620043,0,4650,timeout,0 +620044,1,3894,success,0 +620045,0,4650,timeout,0 +620046,0,4650,timeout,0 +620047,0,4650,timeout,0 +620048,0,4650,timeout,0 +620049,0,4650,timeout,0 +620050,0,4650,timeout,0 +620051,0,4650,timeout,0 +620052,1,3304,success,0 +620053,0,4650,timeout,0 +620054,0,4650,timeout,0 +620055,0,4650,timeout,0 +620056,1,3941,success,0 +620057,1,3632,success,0 +620058,0,4650,timeout,0 +620059,0,4650,timeout,0 +620060,0,4650,timeout,0 +620061,0,4650,timeout,0 +620062,0,4650,timeout,0 +620063,0,4650,timeout,0 +620064,0,4650,timeout,0 +620065,1,3605,success,0 +620066,1,3798,success,0 +620067,1,3773,success,0 +620068,0,4650,timeout,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,0,4650,timeout,0 +620073,1,3874,success,0 +620074,0,4650,timeout,0 +620075,1,3804,success,0 +620076,0,4650,timeout,0 +620077,0,4650,timeout,0 +620078,1,3496,success,0 +620079,0,4650,timeout,0 +620080,0,4650,timeout,0 +620081,0,4650,timeout,0 +620082,0,4650,timeout,0 +620083,1,3636,success,0 +620084,0,4650,timeout,0 +620085,0,4650,timeout,0 +620086,1,3505,success,0 +620087,0,4650,timeout,0 +620088,0,4650,timeout,0 +620089,0,4650,timeout,0 +620090,0,4650,timeout,0 +620091,0,4650,timeout,0 +620092,1,3635,success,0 +620093,0,4650,timeout,0 +620094,1,4155,success,0 +620095,0,4650,timeout,0 +620096,1,3563,success,0 +620097,0,4650,timeout,0 +620098,0,4650,timeout,0 +620099,1,3618,success,0 diff --git a/policies/saucepan_to_hob/opus-s2/kin.py b/policies/saucepan_to_hob/opus-s2/kin.py new file mode 100644 index 0000000000000000000000000000000000000000..7bd0a9f500a0b9920e4e3279c5443e3882a8f4e7 --- /dev/null +++ b/policies/saucepan_to_hob/opus-s2/kin.py @@ -0,0 +1,102 @@ +"""Hand-written forward/inverse kinematics of the G1 arms (URDF constants).""" +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) + + +AX = {'x': _rx, 'y': _ry, 'z': _rz} +HAND = 0.23 # wrist-yaw frame to grasp point, along local x + + +def chain(side): + s = 1.0 if side == 'left' else -1.0 + return [ + # (xyz, rpy, axis) + ((0.0039563, s * 0.10022, 0.24778), (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 = {'left': chain('left'), 'right': chain('right')} + + +def torso_frame(waist): + """Torso pose in the pelvis frame from waist (yaw, roll, pitch).""" + R = _rz(waist[0]) + p = np.zeros(3) + p = 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 p, R + + +def fk(side, q, waist=(0, 0, 0), hand=HAND): + """Grasp point position and rotation in the pelvis frame (x fwd, y left, z up).""" + p, R = torso_frame(waist) + for (xyz, rpy, ax), qi in zip(CH[side], q): + p = p + R @ np.array(xyz) + R = R @ _rpy(*rpy) @ AX[ax](qi) + p = p + R @ np.array([hand, 0, 0]) + return p, 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]) + + +def limits(side): + lo, hi = LO.copy(), HI.copy() + if False: # the action ranges are the same for both arms + lo[1], hi[1] = -HI[1], -LO[1] + lo[2], hi[2] = -HI[2], -LO[2] + lo[4], hi[4] = -HI[4], -LO[4] + lo[6], hi[6] = -HI[6], -LO[6] + return lo, hi + + +def ik(side, target, q0, waist=(0, 0, 0), R_target=None, w_rot=0.3, hand=HAND, reg=0.02, + q_nom=None, w_nom=0.0): + """Least-squares IK for a grasp point position (+ optional orientation). + + q_nom/w_nom optionally pull the redundant joints toward a nominal posture. + """ + lo, hi = limits(side) + q0 = np.clip(np.asarray(q0, float), lo + 1e-3, hi - 1e-3) + + def res(q): + p, R = fk(side, q, waist, hand) + r = [p - target] + if R_target is not None: + r.append(w_rot * (R - R_target).ravel()) + r.append(reg * (q - q0)) + if q_nom is not None: + r.append(w_nom * (q - q_nom)) + return np.concatenate(r) + + sol = least_squares(res, q0, bounds=(lo, hi), xtol=1e-6, ftol=1e-6, max_nfev=200) + p, _ = fk(side, sol.x, waist, hand) + return sol.x, np.linalg.norm(p - target) diff --git a/policies/saucepan_to_hob/opus-s2/policy.py b/policies/saucepan_to_hob/opus-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..cf76cacc35603911babcd83ac7856ba4d96574e2 --- /dev/null +++ b/policies/saucepan_to_hob/opus-s2/policy.py @@ -0,0 +1,690 @@ +"""Saucepan-to-hob policy for the G1 (hand-written state machine). + +Phases: walk to the cabinet, grasp the door handle with the left hand, swing the +door open by walking the base around the hinge, release, then find the saucepan +with the head camera, pick it up by its handle with the right hand and put it on +the hob. +""" + +import cv2 # noqa: F401 +import numpy as np +from scipy.spatial.transform import Rotation as Rot, Slerp + +import cam +import kin + +# ---- scene constants (world frame, identical for every seed) ------------------- +HANDLE = np.array([0.664, 0.274, 0.665]) # door-handle grasp point +HINGE = np.array([0.624, -0.264]) # door hinge (vertical axis), xy +DOOR_R = 0.527 # hinge to handle-grasp radius + +HOOK_R = 0.60 # hook point radius on the door +HOOK_P = np.array([0.30, 0.15]) # hook point in the pelvis frame + +# base waypoints (x, y, yaw, tolerance) from beside the open door to the cabinet front +LEAVE_ROUTE = [(0.33, -0.85, 1.5, 0.08), (-0.40, -0.85, 0.0, 0.08), + (-0.40, 0.15, 0.0, 0.08), (0.20, 0.14, 0.0, 0.05)] + +# saucepan +HANDLE_Z = 0.60 # first guess of the pan handle height (refined by the wrist camera) +GRASP_ALONG = 0.105 # grasp this far right of the rim (the handle points right) +PAN_RIM_R = 0.075 # pan rim radius +ARM_REACH_X = 0.44 # grasp point ahead of the pelvis (arm reaching forward) +ARM_Y = -0.15 # right grasp point beside the pelvis +PRE_BACK = 0.03 +PUSH_MAX = 0.06 # push at most this far past the estimated handle +CAM_X_BIAS = 0.01 # head-camera depth error at the handle +VPUSH_START = 0.15 # (unused) start offset relative to the depth estimate +VPUSH_X0 = 0.74 # the pinch starts here, in front of every handle seen +VPUSH_X1 = 0.97 # and is pushed at most this far (arm reach) +BASE_X_PAN = 0.47 # base x for the grasp (the feet touch the cabinet beyond) +ENTRY_Z = 0.645 # hand height when reaching into the cabinet +VPUSH_MAX = 0.12 # and is pushed at most this far beyond it +U_AXIS = 42.0 # wrist-image column of a handle at the grasp-axis height +VSERVO_GAIN = 0.0008 # m of height per pixel of column error +CAM_Y_BIAS = 0.035 # head-camera lateral bias at the shelf +PAN_SQUAT = 0.63 +REACH_PITCH = 0.45 # lean forward while reaching into the cabinet +SQUAT_BACK = 0.03 # the pelvis moves back this much when squatting +HOB_XY = np.array([0.92, 0.02]) +HOB_Z = 0.90 +PAN_C_OFF = 0.13 # grasp point to pan centre along the handle +CARRY_Z = 1.05 # hand height while carrying the pan over the counter +CARRY_DX = 0.40 # hand ahead of the pelvis while carrying +OUT_X = 0.62 # pull the grasped pan back to here before standing up +PLACE_XY = np.array([0.84, -0.06]) # grasp point when the pan sits on the hob +HOLD_DX = 0.42 # base this far behind the place point while placing +R_PINCH = np.array([[1.0, 0, 0], [0, 0, -1.0], [0, 1.0, 0]]) # roll +90 deg: fingers close vertically +Q_PINCH_SEED = np.array([0.0, 0.0, 0.0, 0.0, 1.5, 0.0, 0.0]) +Q_NOM_R = np.array([-0.5, 0.0, 0.0, 0.5, 0.0, 0.0, 0.0]) # upper arm forward, forearm level + +TUCK_L = np.array([0.20, 0.25, -0.03]) +TUCK_R = np.array([0.15, -0.22, -0.10]) +TUCK_L_PAN = np.array([0.02, 0.24, -0.20]) + + +def rz(a): + c, s = np.cos(a), np.sin(a) + return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1]]) + + +def wrap(a): + return (a + np.pi) % (2 * np.pi) - np.pi + + +class Policy: + def reset(self, obs, tools): + self.tools = tools + self.phase = 'approach' + self.k = 0 # steps in phase + self.q = {'left': np.zeros(7), 'right': np.zeros(7)} + self.grip = [0.6, 0.6] + self.height = 0.70 + self.pitch = 0.0 + self.th_max = 110 + self.th_rate = 0.0022 + self.hooking = False + self.tries = 0 + self.route_k = 0 + self.log = [] + + # ---- helpers -------------------------------------------------------------- + def set_phase(self, p): + self.phase = p + self.k = 0 + + def base(self, l): + return l[21], l[22], l[24] + + def to_pelvis(self, pw, l): + x, y, yaw = self.base(l) + c, s = np.cos(yaw), np.sin(yaw) + d = np.asarray(pw, float) - np.array([x, y, l[23]]) + return np.array([c * d[0] + s * d[1], -s * d[0] + c * d[1], d[2]]) + + def hand_world(self, l, side): + q = l[3:10] if side == 'left' else l[12:19] + p, R = kin.fk(side, q, l[0:3]) + x, y, yaw = self.base(l) + return np.array([x, y, l[23]]) + rz(yaw) @ p, rz(yaw) @ R + + def arm_ik(self, side, p_pelvis, l, R=None, w_rot=1.0, max_step=None): + q, e = kin.ik(side, np.asarray(p_pelvis, float), self.q[side], l[0:3], + R_target=R, w_rot=w_rot) + if max_step is not None: + q = self.q[side] + np.clip(q - self.q[side], -max_step, max_step) + self.q[side] = q + return e + + def walk_cmd(self, l, tx, ty, tyaw, vmax=0.25, kp=1.5, kyaw=1.5): + """Body-frame velocity command toward a world pose.""" + x, y, yaw = self.base(l) + ex, ey = tx - x, ty - y + c, s = np.cos(yaw), np.sin(yaw) + fx, fy = c * ex + s * ey, -s * ex + c * ey + vx, vy = np.clip(kp * fx, -vmax, vmax), np.clip(kp * fy, -vmax, vmax) + sp = np.hypot(vx, vy) + if sp < 0.06: + if sp < 0.02: + vx = vy = 0.0 + else: + vx, vy = vx * 0.06 / sp, vy * 0.06 / sp + wz = float(np.clip(kyaw * wrap(tyaw - yaw), -0.5, 0.5)) + return vx, vy, wz, np.hypot(ex, ey), abs(wrap(tyaw - yaw)) + + def compose(self, tools, vx=0.0, vy=0.0, wz=0.0): + a = np.zeros(21, dtype=np.float32) + a[0], a[1], a[2], a[3], a[4] = vx, vy, self.height, wz, self.pitch + a[5:12] = self.q['left'] + a[12:19] = self.q['right'] + a[19], a[20] = self.grip + return a + + def handle_det(self, im): + im = im.astype(int) + mx = im.max(axis=2) + sat = mx - im.min(axis=2) + m = ((sat < 25) & (mx < 140) & (mx > 40)).astype(np.uint8) + n, lab, stats, cent = cv2.connectedComponentsWithStats(m) + best, bd = None, 1e9 + for i in range(1, n): + x, y, w, h, area = stats[i] + if x <= 1 or x + w >= 83 or w > 30 or h < 12 or area < 40: + continue # finger edges touch the image borders + d = abs(cent[i][0] - 42) + if d < bd: + best, bd = i, d + if best is None: + return None + return cent[best], stats[best] + + # ---- main ----------------------------------------------------------------- + def act(self, obs, tools): + l = np.asarray(obs['low_dim_obs'], dtype=float) + self.k += 1 + fn = getattr(self, 'ph_' + self.phase) + try: + a = fn(l, tools) + except Exception as exc: # never let a numerical hiccup end the episode + self.log.append(('error', self.phase, repr(exc))) + self.set_phase('done') + a = self.compose(tools) + self.last_a = a + return a + + def ph_approach(self, l, tools): + if self.k == 1: + self.q0 = {s: self.q[s].copy() for s in self.q} + self.qt = {} + self.qt['left'] = kin.ik('left', TUCK_L, np.zeros(7), l[0:3], R_target=np.eye(3), w_rot=1.0)[0] + self.qt['right'] = kin.ik('right', TUCK_R, np.zeros(7), l[0:3], R_target=np.eye(3), w_rot=1.0)[0] + a = min(1.0, self.k / 40) + for s in ('left', 'right'): + self.q[s] = self.q0[s] + a * (self.qt[s] - self.q0[s]) + self.grip = [0.5, 0.6] + if self.k < 40: + return self.compose(tools) + tx, ty = HANDLE[0] - 0.32, HANDLE[1] - 0.24 + vx, vy, wz, ep, eyaw = self.walk_cmd(l, tx, ty, 0.0, vmax=0.2) + if (ep < 0.02 and eyaw < 0.04 and self.k > 80) or self.k > 400: + self.set_phase('reach') + return self.compose(tools) + return self.compose(tools, vx, vy, wz) + + def ph_reach(self, l, tools): + if self.k == 1: + self.pre = HANDLE + np.array([-0.07, 0.0, 0.0]) + self.ql0 = self.q['left'].copy() + self.qpre = kin.ik('left', self.to_pelvis(self.pre, l), self.q['left'], l[0:3], + R_target=np.eye(3), w_rot=1.0)[0] + if self.k <= 70: + a = min(1.0, self.k / 40) + self.q['left'] = self.ql0 + a * (self.qpre - self.ql0) + return self.compose(tools) + if self.k == 71: + self.tgt = self.to_pelvis(self.pre, l) + self.adv = 0.0 + self.trk0 = np.abs(l[3:10] - self.q['left']) + # visual servo: centre the handle, advance 1 cm every 6 steps + if (self.k - 71) % 6 == 0: + det = self.handle_det(tools.image('left_wrist')) + du = 0.0 if det is None else det[0][0] - 42 + self.tgt[1] += np.clip(-0.0015 * du, -0.01, 0.01) + if abs(du) < 5: + self.tgt[0] += 0.01 + self.adv += 0.01 + self.arm_ik('left', self.tgt, l, R=np.eye(3)) + trk = np.abs(np.abs(l[3:10] - self.q['left']) - self.trk0).max() + self.log.append(('reach', self.k, du, self.adv, trk)) + if self.adv >= 0.085 or (trk > 0.1 and self.adv > 0.04) or self.k > 400: + self.set_phase('grasp') + return self.compose(tools) + + def ph_grasp(self, l, tools): + self.grip[0] = 1.0 + if self.k == 1: + self.q['left'] = l[3:10].copy() # stop pushing + if self.k > 30: + if l[10] > -0.017: # fingers blocked by the handle: holding it + self.set_phase('pull') + else: + self.grip[0] = 0.5 + self.set_phase('reach') + return self.compose(tools) + + def ph_pull(self, l, tools): + """Walk the base around the hinge, keeping the hand fixed in the pelvis frame.""" + hw, _ = self.hand_world(l, 'left') + v = hw[:2] - HINGE + th = np.arctan2(-v[0], v[1]) + if self.k == 1: + self.th_hist = [] + self.p_hand = self.to_pelvis(hw, l) # hand offset in the pelvis frame + self.th_d = th + self.r_pull = np.linalg.norm(v) + self.yaw0 = wrap(l[24] - th) + self.th_d = min(self.th_d + self.th_rate, th + 0.10, np.deg2rad(self.th_max)) + hd = HINGE + self.r_pull * np.array([-np.sin(self.th_d), np.cos(self.th_d)]) + yaw_d = self.yaw0 + self.th_d # the door turns counter-clockwise as it opens + off = rz(yaw_d)[:2, :2] @ self.p_hand[:2] + # yaw0 + th: keep the pelvis-to-handle pose as it was at the grasp + bx, by = hd - off + vx, vy, wz, ep, eyaw = self.walk_cmd(l, bx, by, yaw_d, vmax=0.2, kp=2.5, kyaw=2.5) + self.log.append((self.k, th, self.th_d, hw.copy(), l[21:25].copy(), l[10])) + self.th_door = th + self.th_hist.append(th) + stalled = (len(self.th_hist) > 100 and th > np.deg2rad(60) + and th - self.th_hist[-100] < np.deg2rad(1.0)) + if self.hooking: + if th > np.deg2rad(self.th_max - 5) or stalled or self.k > 900: + self.set_phase('leave') + elif th > np.deg2rad(self.th_max - 2) or stalled or self.k > 1500: + self.set_phase('leave') + elif l[10] < -0.0175: # slipped off the handle + self.set_phase('leave' if th > np.deg2rad(60) else 'release') + return self.compose(tools, vx, vy, wz) + + def ph_leave(self, l, tools): + """Let go of the open door and walk around it to the front of the cabinet.""" + th = self.th_door + if self.k == 1: + self.grip[0] = 0.0 + hw, _ = self.hand_world(l, 'left') + n_out = np.array([-np.cos(th), -np.sin(th)]) + back = hw[:2] + 0.10 * n_out + self.lq0 = self.q['left'].copy() + self.lq1 = kin.ik('left', self.to_pelvis([back[0], back[1], hw[2]], l), + self.q['left'], l[0:3])[0] + self.lq2 = kin.ik('left', TUCK_L, self.lq1, l[0:3], R_target=np.eye(3), w_rot=1.0)[0] + self.route = list(LEAVE_ROUTE) + if self.k <= 15: + return self.compose(tools) + if self.k <= 40: + a = (self.k - 15) / 25 + self.q['left'] = self.lq0 + a * (self.lq1 - self.lq0) + return self.compose(tools) + if self.k <= 70: + a = (self.k - 40) / 30 + self.q['left'] = self.lq1 + a * (self.lq2 - self.lq1) + return self.compose(tools) + if not self.route: + self.set_phase('pan_look') + return self.compose(tools) + tx, ty, tyaw, tol = self.route[0] + vx, vy, wz, ep, eyaw = self.walk_cmd(l, tx, ty, tyaw, vmax=0.35) + self.route_k = getattr(self, 'route_k', 0) + 1 + if (ep < tol and eyaw < 0.15) or self.route_k > 500: + self.route_k = 0 + self.route.pop(0) + return self.compose(tools, vx, vy, wz) + + def door_pt(self, th, r, off): + """World xy of a point on the door: radius r from the hinge, offset off + towards the cabinet inside (+) or outside (-).""" + d = np.array([-np.sin(th), np.cos(th)]) + n_in = np.array([np.cos(th), np.sin(th)]) + return HINGE + r * d + off * n_in + + def ph_release(self, l, tools): + """Let go of the handle and bring the hand behind the door's free edge.""" + th = self.th_door + z = HANDLE[2] + if self.k == 1: + self.grip[0] = 0.0 + self.wps = [(self.door_pt(th, 0.675, -0.10), 25), ('walk', 0), + (self.door_pt(th, 0.88, -0.08), 30), + (self.door_pt(th, 0.88, 0.08), 30), + (self.door_pt(th, HOOK_R, 0.06), 40)] + self.wi = 0 + self.wk = 0 + # base pose that puts the hook point at HOOK_P in the pelvis frame + hp = self.door_pt(th, HOOK_R, 0.06) + self.hook_base = (hp - rz(th)[:2, :2] @ HOOK_P[:2], th) + if self.k < 15: + return self.compose(tools) + if self.wi < len(self.wps) and isinstance(self.wps[self.wi][0], str): + (bx, by), byaw = self.hook_base + vx, vy, wz, ep, eyaw = self.walk_cmd(l, bx, by, byaw, vmax=0.15) + self.wk += 1 + if (ep < 0.025 and eyaw < 0.05 and self.wk > 20) or self.wk > 300: + self.wi += 1 + self.wk = 0 + return self.compose(tools) + return self.compose(tools, vx, vy, wz) + if self.wi < len(self.wps): + if self.wk == 0: + p, n = self.wps[self.wi] + pt = self.to_pelvis([p[0], p[1], z], l) + self.wq0 = self.q['left'].copy() + self.wq1 = kin.ik('left', pt, self.q['left'], l[0:3], + R_target=rz(-th - l[24]) if False else None)[0] + self.wn = n + self.wk += 1 + a = min(1.0, self.wk / self.wn) + self.q['left'] = self.wq0 + a * (self.wq1 - self.wq0) + if self.wk >= self.wn + 5: + self.wi += 1 + self.wk = 0 + return self.compose(tools) + self.grip[0] = 1.0 + self.hooking = True + self.th_max = 110 + self.set_phase('pull') + return self.compose(tools) + + def ph_unhook(self, l, tools): + self.grip[0] = 0.0 + if self.k > 25: + self.set_phase('done') + return self.compose(tools) + + # ---- saucepan ------------------------------------------------------------- + def world_of(self, p, l): + x, y, yaw = self.base(l) + return np.array([x, y, l[23]]) + rz(yaw) @ p + + def detect_pan(self, im, l): + """Pan centre (pixels) and the handle as 3D points at handle height.""" + imi = im.astype(int) + r, g, b = imi[..., 0], imi[..., 1], imi[..., 2] + m = ((r > g + 25) & (g > b) & (r > 70)).astype(np.uint8) + n, lab, stats, cent = cv2.connectedComponentsWithStats(m) + if n <= 1: + return None + i = 1 + int(np.argmax(stats[1:, cv2.CC_STAT_AREA])) + if stats[i, cv2.CC_STAT_AREA] < 25: + return None + cu, cv_ = cent[i] + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(int) + hm = (hsv[..., 1] > 35) & (hsv[..., 0] >= 8) & (hsv[..., 0] <= 30) & (hsv[..., 2] > 100) + hm &= lab != i + vv, uu = np.mgrid[0:84, 0:84] + d = np.hypot(uu - cu, vv - cv_) + rad = np.sqrt(stats[i, cv2.CC_STAT_AREA] / np.pi) + hm &= (d > rad - 0.5) & (d < rad + 18) & (np.abs(vv - cv_) < 12) + # keep the blob that starts at the pan rim and is not the long counter edge + nh, labh, sth, _ = cv2.connectedComponentsWithStats(hm.astype(np.uint8)) + keep = np.zeros_like(hm) + for j in range(1, nh): + x0, y0, ww, hh, area = sth[j] + if ww > 30 or area < 2: + continue + if d[labh == j].min() < rad + 3: + keep |= labh == j + hm = keep + if hm.sum() < 3: + return None + w = l[0:3] + pts = np.array([self.world_of(cam.ray_plane_z(u, v, w, HANDLE_Z - l[23]), l) + for v, u in zip(*np.nonzero(hm))]) + pc = self.world_of(cam.ray_plane_z(cu, cv_, w, HANDLE_Z - l[23]), l) + dv = pts[:, :2] - pc[:2] + dist = np.linalg.norm(dv, axis=1) + hd = (dv / dist[:, None]).mean(0) + hd /= np.linalg.norm(hd) + root = pc[:2] + PAN_RIM_R * hd + return root, hd, pc[:2] + + def ph_pan_look(self, l, tools): + self.height, self.pitch = 0.70, 0.0 + self.grip = [0.0, 0.0] + if self.k == 1: + self.dets = [] + # fold the left arm close to the body so it cannot catch the cabinet front + self.lq0 = self.q['left'].copy() + self.lq1 = kin.ik('left', TUCK_L_PAN, self.q['left'], l[0:3])[0] + if self.k <= 40: + self.q['left'] = self.lq0 + min(1.0, self.k / 30) * (self.lq1 - self.lq0) + if self.k > 50 and self.k % 5 == 0: + det = self.detect_pan(tools.image('head'), l) + if det is not None: + self.dets.append(det) + if len(self.dets) >= 4 or (self.k > 150 and self.dets): + root = np.median([d[0] for d in self.dets], axis=0) + hd = np.median([d[1] for d in self.dets], axis=0) + hd /= np.linalg.norm(hd) + self.pan_hd = hd + self.pan_c = np.median([d[2] for d in self.dets], axis=0) + # the handle always points roughly to the right (-y), give or take 30 deg; + # its measured direction is unreliable, so grasp straight right of the pan + g = self.pan_c + np.array([0.0, -(PAN_RIM_R + GRASP_ALONG)]) + self.grasp = np.array([g[0] + CAM_X_BIAS, g[1] + CAM_Y_BIAS, HANDLE_Z]) + self.set_phase('pan_walk') + if self.k > 400: + self.set_phase('done') + return self.compose(tools) + + def ph_pan_walk(self, l, tools): + tx = BASE_X_PAN # as close as the feet allow; the pan depth estimate is too noisy + ty = self.grasp[1] - ARM_Y + vx, vy, wz, ep, eyaw = self.walk_cmd(l, tx, ty, 0.0, vmax=0.15) + if (ep < 0.02 and eyaw < 0.04 and self.k > 20) or self.k > 300: + self.start_pan_seq(l) + return self.compose(tools) + return self.compose(tools, vx, vy, wz) + + def arm_world(self, side, pw, l, R_world, seed=None): + """IK for a world pose, kept near a forward-reaching elbow-low posture.""" + pt = self.to_pelvis(pw, l) + Rp = rz(-l[24]) @ R_world + q0 = self.q[side] if seed is None else seed + if side == 'right': + qn = Q_NOM_R.copy() + qn[4] = 1.57 if Rp[2, 1] > 0.5 else 0.0 + q, e = kin.ik(side, pt, q0, l[0:3], R_target=Rp, w_rot=1.0, q_nom=qn, w_nom=0.05) + q, e = kin.ik(side, pt, q, l[0:3], R_target=Rp, w_rot=1.0, q_nom=qn, w_nom=0.005) + else: + q, e = kin.ik(side, pt, q0, l[0:3], R_target=Rp, w_rot=1.0) + return q, e + + # Cartesian sequence for the right hand ------------------------------------- + def start_pan_seq(self, l): + g = self.grasp + hw, R0 = self.hand_world(l, 'right') + self.cp, self.cR = hw.copy(), R0.copy() + self.sag = np.zeros(3) + self.seq = [ + dict(t='height', v=PAN_SQUAT, pitch=REACH_PITCH, n=40), + dict(t='grip', v=0.0, n=1), + # enter above the bottom rail of the cabinet opening, then let the + # wrist-camera servo bring the hand down to the handle + dict(t='move', to=[0.58, g[1], ENTRY_Z], R=R_PINCH, n=45), + dict(t='move', to=[VPUSH_X0, g[1], ENTRY_Z], R=R_PINCH, n=35), + dict(t='vpush'), + dict(t='grip', v=1.0, n=35), + dict(t='check'), + dict(t='move', to='lift', R=R_PINCH, n=30), + dict(t='move', to='out', R=R_PINCH, n=50), + dict(t='height', v=0.70, pitch=0.0, n=40), + dict(t='walkrel', dx=-0.42), + dict(t='move', to='high', R=R_PINCH, n=60), + dict(t='walkto', x='hob_base'), + dict(t='move', to='over_hob', R=R_PINCH, n=50), + dict(t='place'), + dict(t='grip', v=0.0, n=30), + dict(t='move', to='retreat', R=R_PINCH, n=40), + ] + self.si, self.sk = 0, 0 + self.set_phase('pan_seq') + + def resolve(self, to): + g = self.grasp + if not isinstance(to, str): + return np.array(to, float) + if to == 'up_back': + return self.cp + [-0.06, 0, 0.03] + if to == 'pre': + self.gx = g[0] - PRE_BACK - 0.04 + return np.array([self.gx, g[1], g[2]]) + if to == 'lift': + return self.cp + [0, 0, 0.03] + if to == 'out': + return np.array([OUT_X, self.cp[1], self.cp[2] + 0.01]) + if to == 'high': # arm reaching forward and up, clear of the counter edge + l = self.l_now + p = self.world_of(np.array([CARRY_DX, ARM_Y, 0.0]), l) + return np.array([p[0], self.cp[1], CARRY_Z]) + if to == 'over_hob': + return np.array([PLACE_XY[0], PLACE_XY[1], CARRY_Z]) + if to == 'retreat': + return self.cp + [-0.15, 0, 0.06] + raise ValueError(to) + + def track(self, l, p, R, integrate=True): + """Command the right hand to world pose (p, R) with sag compensation.""" + hw, _ = self.hand_world(l, 'right') + if integrate: + self.sag = np.clip(self.sag + 0.05 * (self.cp - hw), -0.15, 0.15) + self.sag[:2] = np.clip(self.sag[:2], -0.02, 0.02) + q, e = self.arm_world('right', np.asarray(p, float) + self.sag, l, R) + self.q['right'] = q + return hw, e + + def handle_col(self, im): + """Mean image column of the pan handle in the rolled right-wrist view.""" + hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV).astype(int) + imi = im.astype(int) + r = imi[..., 0] + 1 + m = ((hsv[..., 0] >= 10) & (hsv[..., 0] <= 30) & (hsv[..., 1] > 50) & + (hsv[..., 2] > 110) & (imi[..., 1] > 0.76 * r)) # wood, not copper + m[:, :18] = False # the counter edge shows up on the far left (world up) + if m.sum() < 4: + return None + ys, xs = np.nonzero(m) + return float(np.median(xs)) + + def ph_pan_seq(self, l, tools): + self.l_now = l + if self.si >= len(self.seq): + self.set_phase('done') + return self.compose(tools) + s = self.seq[self.si] + self.sk += 1 + k = self.sk + t = s['t'] + nxt = False + if t == 'height': + self.height = s['v'] + self.pitch = s.get('pitch', self.pitch) + self.track(l, self.cp, self.cR) + nxt = k >= s['n'] + elif t == 'grip': + self.grip[1] = s['v'] + nxt = k >= s['n'] + elif t == 'move': + if k == 1: + self.m0, self.m1 = self.cp.copy(), self.resolve(s['to']) + self.r0, self.r1 = Rot.from_matrix(self.cR), Rot.from_matrix(s['R']) + a = min(1.0, k / max(1, s['n'] - 8)) + self.cp = self.m0 + a * (self.m1 - self.m0) + self.cR = (Slerp([0, 1], Rot.concatenate([self.r0, self.r1]))([a])[0]).as_matrix() + self.track(l, self.cp, self.cR) + nxt = k >= s['n'] + elif t == 'probe': + # lower 4 mm every 4 steps until the hand stops following + hw, _ = self.hand_world(l, 'right') + if k <= 20: # let the arm settle first + self.pz0 = self.cp[2] - hw[2] + self.track(l, self.cp, self.cR) + return self.compose(tools) + if k % 4 == 0: + lag = hw[2] - (self.cp[2] - self.pz0) + self.log.append(('probe', round(self.cp[2], 3), round(hw[2], 3), round(lag, 3))) + if lag > 0.012 or self.cp[2] < 0.66: + z = hw[2] - 0.016 if lag > 0.012 else HANDLE_Z + self.grasp[2] = float(np.clip(z, HANDLE_Z - 0.03, HANDLE_Z + 0.03)) + self.cp[2] = hw[2] + nxt = True + else: + self.cp[2] -= 0.004 + self.track(l, self.cp, self.cR, integrate=False) + elif t == 'push': + hw, _ = self.hand_world(l, 'right') + if k == 1: + self.push_x0 = l[21] + self.lag0 = self.cp[0] - hw[0] + if k % 6 == 0: + lag = self.cp[0] - hw[0] - self.lag0 + pushed = self.push_x0 - l[21] # the base being shoved back + self.log.append(('push', round(self.cp[0], 3), round(hw[0], 3), round(lag, 3), round(hw[2], 3), round(pushed, 3))) + if ((lag > 0.02 or pushed > 0.02) and k > 24) or self.cp[0] > self.grasp[0] + PUSH_MAX: + nxt = True + else: + self.cp[0] += 0.01 + # hold the height tightly (the arm droops as it extends), not x + self.sag[2] = np.clip(self.sag[2] + 0.15 * (self.cp[2] - hw[2]), -0.15, 0.15) + self.track(l, self.cp, self.cR, integrate=False) + elif t == 'vpush': + # The wrist camera sits beside the grasp axis once the hand is rolled, so a + # horizontal handle at the axis height images onto the centre column. + hw, _ = self.hand_world(l, 'right') + if k == 1: + self.push_x0 = l[21] + self.xhist = [] + self.n_rest = 0 + self.vx0 = self.cp[0] + if k % 4 == 0: + u = self.handle_col(tools.image('right_wrist')) + self.xhist.append((self.cp[0], hw[0])) + lag = 0.0 + if len(self.xhist) > 5: # commanded advance vs achieved advance + c0, h0 = self.xhist[-6] + if self.cp[0] - c0 >= 0.024: + lag = (self.cp[0] - c0) - (hw[0] - h0) + pushed = self.push_x0 - l[21] + self.log.append(('vpush', round(self.cp[0], 3), round(self.cp[2], 3), round(hw[0], 3), + round(hw[2], 3), None if u is None else round(u, 1), round(lag, 3), round(pushed, 3))) + if lag > 0.015 or (pushed > 0.025 and k > 16) or self.cp[0] > VPUSH_X1: + nxt = True + else: + if hw[2] - self.cp[2] > 0.025 and self.n_rest < 2: + # a finger is resting on top of the handle: back off and drop + self.n_rest += 1 + self.cp[0] = max(self.cp[0] - 0.02, self.vx0 - 0.03) + self.cp[2] = hw[2] - 0.015 + elif u is not None: + self.cp[2] += float(np.clip(VSERVO_GAIN * (U_AXIS - u), -0.004, 0.004)) + elif self.cp[2] > HANDLE_Z - 0.03: + self.cp[2] -= 0.003 # handle not in view yet: it is lower + self.cp[2] = max(self.cp[2], 0.50) + if u is None or abs(u - U_AXIS) < 6 or k % 32 == 0: + self.cp[0] += 0.006 + if k > 320: + nxt = True + self.sag[2] = np.clip(self.sag[2] + 0.15 * (self.cp[2] - hw[2]), -0.15, 0.15) + self.track(l, self.cp, self.cR, integrate=False) + elif t in ('walkrel', 'walkto'): + # walk the base while the hand stays fixed relative to the pelvis + if k == 1: + self.w_off = self.to_pelvis(self.cp, l) + x, y, yaw = self.base(l) + if t == 'walkrel': + self.w_tgt = (x + s['dx'], y) + else: + self.w_tgt = (PLACE_XY[0] - HOLD_DX, PLACE_XY[1] - self.w_off[1]) + self.cp = self.world_of(self.w_off, l) + vx, vy, wz, ep, eyaw = self.walk_cmd(l, self.w_tgt[0], self.w_tgt[1], 0.0, vmax=0.12) + self.track(l, self.cp, self.cR) + if (ep < 0.025 and eyaw < 0.05 and k > 20) or k > 400: + self.si, self.sk = self.si + 1, 0 + return self.compose(tools) + return self.compose(tools, vx, vy, wz) + elif t == 'check': + self.log.append(('pan_grasp', round(self.cp[0], 3), l[19])) + if l[19] < -0.017: # fingers closed on nothing: retry from a new start + self.tries = getattr(self, 'tries', 0) + 1 + if self.tries > 3: + self.set_phase('done') + return self.compose(tools) + hw, _ = self.hand_world(l, 'right') + dy = [0.0, 0.03, -0.03][self.tries % 3] + y = self.grasp[1] + dy + x0 = max(VPUSH_X0 - 0.03, min(hw[0] - 0.10, VPUSH_X0)) + retry = [dict(t='grip', v=0.0, n=15), + dict(t='move', to=[hw[0] - 0.04, hw[1], ENTRY_Z], R=R_PINCH, n=30), + dict(t='move', to=[x0, y, ENTRY_Z], R=R_PINCH, n=30), + dict(t='vpush'), + dict(t='grip', v=1.0, n=35), + dict(t='check')] + self.seq = self.seq[:self.si + 1] + retry + self.seq[self.si + 1:] + nxt = True + elif t == 'place': + hw, _ = self.hand_world(l, 'right') + if k <= 25: # settle above the hob first + self.pz0 = self.cp[2] - hw[2] + self.track(l, self.cp, self.cR) + return self.compose(tools) + if k % 4 == 0: + lag = hw[2] - (self.cp[2] - self.pz0) + self.log.append(('place', round(self.cp[2], 3), round(hw[2], 3), round(lag, 3))) + if lag > 0.015 or self.cp[2] < HOB_Z - 0.05: + nxt = True + else: + self.cp[2] -= 0.004 + self.track(l, self.cp, self.cR, integrate=False) + if nxt: + self.si, self.sk = self.si + 1, 0 + return self.compose(tools) + + def ph_done(self, l, tools): + return self.compose(tools) diff --git a/policies/saucepan_to_hob/opus-s3/camera.py b/policies/saucepan_to_hob/opus-s3/camera.py new file mode 100644 index 0000000000000000000000000000000000000000..ac983c37fb9850a15421f3706f45ba740f8f89be --- /dev/null +++ b/policies/saucepan_to_hob/opus-s3/camera.py @@ -0,0 +1,42 @@ +"""Head-camera model (fitted on the floor checkerboard + hand positions) and pixel <-> world helpers.""" +import numpy as np + +import g1fk + +CAM_F = 53.3484 +CAM_PITCH = 1.1253 +CAM_DZ = -0.1569 +CAM_DX = 0.1428 +CAM_YAW = 0.0107 +CAM_ROLL = -0.0085 + + +def cam_world(pose, waist): + """World rotation and origin of the head camera for pelvis pose (x, y, z, yaw).""" + T = g1fk.head_cam_T(waist, xyz=(0.0576 + CAM_DX, 0.0175, 0.43 + CAM_DZ), pitch=CAM_PITCH) + T[:3, :3] = T[:3, :3] @ g1fk._rz(CAM_YAW) @ g1fk._rx(CAM_ROLL) + Rz = g1fk._rz(pose[3]) + return Rz @ T[:3, :3], np.array(pose[:3], float) + Rz @ T[:3, 3] + + +def pixel_ray(u, v, pose, waist): + """World ray (origin, unit direction) through pixel (u, v) given as 0-based indices.""" + R, o = cam_world(pose, waist) + d = R @ np.array([1.0, (41.5 - u) / CAM_F, (41.5 - v) / CAM_F]) + return o, d / np.linalg.norm(d) + + +def pixel_to_plane_z(u, v, z, pose, waist): + o, d = pixel_ray(u, v, pose, waist) + return o + (z - o[2]) / d[2] * d + + +def pixel_to_plane_x(u, v, x, pose, waist): + o, d = pixel_ray(u, v, pose, waist) + return o + (x - o[0]) / d[0] * d + + +def world_to_pixel(P, pose, waist): + R, o = cam_world(pose, waist) + c = R.T @ (np.asarray(P, float) - o) + return np.array([41.5 - CAM_F * c[1] / c[0], 41.5 - CAM_F * c[2] / c[0]]), c[0] diff --git a/policies/saucepan_to_hob/opus-s3/episodes.csv b/policies/saucepan_to_hob/opus-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8bdd4e6043da73ac776c1ce5081f089e7a50e206 --- /dev/null +++ b/policies/saucepan_to_hob/opus-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,4650,timeout,0 +620001,0,4650,timeout,0 +620002,0,4650,timeout,0 +620003,0,4650,timeout,0 +620004,0,4650,timeout,0 +620005,0,4650,timeout,0 +620006,0,4650,timeout,0 +620007,0,4650,timeout,0 +620008,0,4650,timeout,0 +620009,0,4650,timeout,0 +620010,0,4650,timeout,0 +620011,0,4650,timeout,0 +620012,0,4650,timeout,0 +620013,0,4650,timeout,0 +620014,0,4650,timeout,0 +620015,0,4650,timeout,0 +620016,0,4650,timeout,0 +620017,0,4650,timeout,0 +620018,0,4650,timeout,0 +620019,0,4650,timeout,0 +620020,0,4650,timeout,0 +620021,0,4650,timeout,0 +620022,0,4650,timeout,0 +620023,0,4650,timeout,0 +620024,0,4650,timeout,0 +620025,0,4650,timeout,0 +620026,0,4650,timeout,0 +620027,0,4650,timeout,0 +620028,0,4650,timeout,0 +620029,0,4650,timeout,0 +620030,0,4650,timeout,0 +620031,0,4650,timeout,0 +620032,0,4650,timeout,0 +620033,0,4650,timeout,0 +620034,0,4650,timeout,0 +620035,0,4650,timeout,0 +620036,0,4650,timeout,0 +620037,0,4650,timeout,0 +620038,0,4650,timeout,0 +620039,0,4650,timeout,0 +620040,0,4650,timeout,0 +620041,0,4650,timeout,0 +620042,0,4650,timeout,0 +620043,0,4650,timeout,0 +620044,0,4650,timeout,0 +620045,0,4650,timeout,0 +620046,0,4650,timeout,0 +620047,0,4650,timeout,0 +620048,0,4650,timeout,0 +620049,0,4650,timeout,0 +620050,0,4650,timeout,0 +620051,0,4650,timeout,0 +620052,0,4650,timeout,0 +620053,0,4650,timeout,0 +620054,0,4650,timeout,0 +620055,0,4650,timeout,0 +620056,0,4650,timeout,0 +620057,0,4650,timeout,0 +620058,0,4650,timeout,0 +620059,0,4650,timeout,0 +620060,0,4650,timeout,0 +620061,0,4650,timeout,0 +620062,0,4650,timeout,0 +620063,0,4650,timeout,0 +620064,0,4650,timeout,0 +620065,0,4650,timeout,0 +620066,0,4650,timeout,0 +620067,0,4650,timeout,0 +620068,0,4650,timeout,0 +620069,0,4650,timeout,0 +620070,0,4650,timeout,0 +620071,0,4650,timeout,0 +620072,0,4650,timeout,0 +620073,0,4650,timeout,0 +620074,0,4650,timeout,0 +620075,0,4650,timeout,0 +620076,0,4650,timeout,0 +620077,0,4650,timeout,0 +620078,0,4650,timeout,0 +620079,0,4650,timeout,0 +620080,0,4650,timeout,0 +620081,0,4650,timeout,0 +620082,0,4650,timeout,0 +620083,0,4650,timeout,0 +620084,0,4650,timeout,0 +620085,0,4650,timeout,0 +620086,0,4650,timeout,0 +620087,0,4650,timeout,0 +620088,0,4650,timeout,0 +620089,0,4650,timeout,0 +620090,0,4650,timeout,0 +620091,0,4650,timeout,0 +620092,0,4650,timeout,0 +620093,0,4650,timeout,0 +620094,0,4650,timeout,0 +620095,0,4650,timeout,0 +620096,0,4650,timeout,0 +620097,0,4650,timeout,0 +620098,0,4650,timeout,0 +620099,0,4650,timeout,0 diff --git a/policies/saucepan_to_hob/opus-s3/g1fk.py b/policies/saucepan_to_hob/opus-s3/g1fk.py new file mode 100644 index 0000000000000000000000000000000000000000..9caec528f40aaef3b0006e81d11da0d8c3f32cf7 --- /dev/null +++ b/policies/saucepan_to_hob/opus-s3/g1fk.py @@ -0,0 +1,141 @@ +"""Approximate forward kinematics of the Unitree G1 upper body (from the public URDF).""" +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, p): + T = np.eye(4) + T[:3, :3] = R + T[:3, 3] = p + return T + + +_AX = {"x": _rx, "y": _ry, "z": _rz} + + +def torso_T(waist): + """Pelvis -> torso transform from waist yaw, roll, pitch.""" + T = _T(_rz(waist[0]), [0, 0, 0]) + T = T @ _T(_rx(waist[1]), [-0.0039635, 0, 0.044]) + T = T @ _T(_ry(waist[2]), [0, 0, 0]) + return T + + +def arm_chain(side): + s = 1.0 if side == "left" else -1.0 + return [ + ([0.0039563, s * 0.10022, 0.23778], _rpy(s * 0.27931, 5.4949e-05, -s * 0.00019159), "y"), + ([0, s * 0.038, -0.013831], _rpy(-s * 0.27925, 0, 0), "x"), + ([0, s * 0.00624, -0.1032], np.eye(3), "z"), + ([0.015783, 0, -0.080518], np.eye(3), "y"), + ([0.100, s * 0.00188791, -0.010], np.eye(3), "x"), + ([0.038, 0, 0], np.eye(3), "y"), + ([0.046, 0, 0], np.eye(3), "z"), + ] + + +def arm_fk(side, q, waist=(0, 0, 0), tool=(0.10, 0, 0), all_frames=False): + """Return pelvis-frame 4x4 of the tool point on the hand (and optionally all joint frames).""" + T = torso_T(waist) + frames = [] + for (p, R0, ax), qi in zip(arm_chain(side), q): + T = T @ _T(R0, p) @ _T(_AX[ax](qi), [0, 0, 0]) + frames.append(T.copy()) + Tt = T @ _T(np.eye(3), list(tool)) + if all_frames: + return Tt, frames + return Tt + + +def head_cam_T(waist=(0, 0, 0), xyz=(0.0576235, 0.01753, 0.42987), pitch=0.8307767): + """Pelvis-frame pose of the head camera (x forward, y left, z up body convention).""" + return torso_T(waist) @ _T(_ry(pitch), list(xyz)) + + +def project(cam_T, pts, f, cx=41.5, cy=41.5): + """Project pelvis-frame points into an 84x84 image; camera looks along its +x.""" + inv = np.linalg.inv(cam_T) + P = (inv[:3, :3] @ np.asarray(pts).T).T + inv[:3, 3] + # camera +x forward, +y left, +z up -> u right = -y, v down = -z + u = cx - f * P[:, 1] / P[:, 0] + v = cy - f * P[:, 2] / P[:, 0] + return np.stack([u, v], 1), P[:, 0] + + +LIMITS = np.array([ + [-3.0892, 2.6704], [-1.5882, 2.2515], [-2.618, 2.618], [-1.0472, 2.0944], + [-1.97222, 1.97222], [-1.61443, 1.61443], [-1.61443, 1.61443]]) + + +def limits(side): + lim = LIMITS.copy() + if side == "right": + lim[1] = [-2.2515, 1.5882] + return lim + + +def rot_err(Ra, Rb): + """Axis-angle vector of Ra^T Rb.""" + R = Ra.T @ Rb + w = np.array([R[2, 1] - R[1, 2], R[0, 2] - R[2, 0], R[1, 0] - R[0, 1]]) / 2 + return w + + +def ik(side, pos, R=None, q0=None, waist=(0, 0, 0), tool=(0.10, 0, 0), wrot=0.3, + wreg=0.02, qnom=None, axis_only=None): + """Least-squares IK for the tool point. + + R: desired 3x3 rotation of the tool frame (pelvis frame), or None. + axis_only: (local_axis, world_dir) to constrain only one axis direction. + """ + from scipy.optimize import least_squares + lim = limits(side) + q0 = np.zeros(7) if q0 is None else np.asarray(q0, float) + qn = q0 if qnom is None else np.asarray(qnom, float) + + def res(q): + T = arm_fk(side, q, waist, tool) + r = list(T[:3, 3] - pos) + if R is not None: + r += list(wrot * rot_err(T[:3, :3], R)) + if axis_only is not None: + la, wd = axis_only + r += list(wrot * (T[:3, :3] @ np.asarray(la) - np.asarray(wd))) + r += list(wreg * (q - qn)) + return np.array(r) + + s = least_squares(res, np.clip(q0, lim[:, 0] + 1e-3, lim[:, 1] - 1e-3), + bounds=(lim[:, 0], lim[:, 1])) + T = arm_fk(side, s.x, waist, tool) + return s.x, np.linalg.norm(T[:3, 3] - pos) + + +def ik_multi(side, pos, R, q0, waist, tool=(0.10, 0, 0), wrot=1.0, n=12, seed=0): + """IK from the current configuration plus deterministic random restarts; prefers small motion.""" + rng = np.random.default_rng(seed) + best = None + starts = [np.asarray(q0, float)] + [rng.uniform(-1.5, 1.5, 7) for _ in range(n)] + for k, s in enumerate(starts): + q, e = ik(side, pos, R=R, q0=s, qnom=q0, waist=waist, tool=tool, wrot=wrot, wreg=0.005) + score = e + 0.002 * np.linalg.norm(q - q0) + if best is None or score < best[2]: + best = (q, e, score) + return best[0], best[1] diff --git a/policies/saucepan_to_hob/opus-s3/policy.py b/policies/saucepan_to_hob/opus-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..6e2a0da5f777fb55abc6e906e20d556ff0e69d28 --- /dev/null +++ b/policies/saucepan_to_hob/opus-s3/policy.py @@ -0,0 +1,406 @@ +"""Saucepan-to-hob policy for the simulated Unitree G1. + +Hand-written controller, structured as a generator script: ``_script`` yields one +action per control step and reads the latest observation from ``self.obs``. + +Phases + 1. Open the cabinet door with the right hand in several pull stages (grasp the + handle with visual servoing on the right wrist camera, pull along the door + arc with a compliant follow-the-hand law, re-station, repeat). + 2. Walk to a station in front of the shelf, squat and lean. + 3. Locate the saucepan handle in the head camera, grasp it with the right hand. + 4. Slide the pan out, lift it above the counter top, move it over the hob, + lower until contact, release and withdraw. +""" + +import cv2 +import numpy as np + +import g1fk +import camera +import vision + +DEBUG = False + +HINGE = np.array([0.53, -0.23]) # door hinge (world xy), fixed across seeds +HANDLE0 = np.array([0.522, 0.27]) # closed door handle position +REL = np.array([0.37, -0.15]) # handle position in the stance frame while pulling +TUCK_R = np.array([0.4, -0.15, 0.0, 0.6, 0.0, 0.0, 0.0]) +TUCK_L = np.array([0.4, 0.15, 0.0, 0.6, 0.0, 0.0, 0.0]) +R_PAN = g1fk._rz(np.pi / 2) # hand pointing +y (along the handle) +GRASP_Z = 0.64 +GRASP_DX = 0.02 +GRASP_DY = 0.03 +GRASP_YAW = 0.6 +UNFOLD = np.array([-0.6, -0.25, 0.0, 0.9, 0.0, 0.0, 0.0]) +SLIDE = 0.22 +CARRY_PITCH = 0.35 +LIFT_Z = 0.95 +HOB_X = 0.66 + + +def wrap(a): + return (a + np.pi) % (2 * np.pi) - np.pi + + +def door_theta(h): + return np.arctan2(-(h[0] - HINGE[0]), h[1] - HINGE[1]) + + +def log(*a): + if DEBUG: + print(*a, flush=True) + + +class Policy: + def reset(self, obs, tools): + self.tools = tools + self.obs = obs + self.a = np.asarray(tools.hold_action(), dtype=np.float64) + self.gen = self._script() + self.info = {} + + def act(self, obs, tools): + self.obs = obs + try: + a = next(self.gen) + except StopIteration: + self.gen = self._idle() + a = next(self.gen) + return np.asarray(a, dtype=np.float32) + + # ------------------------------------------------------------------ helpers + @property + def lo(self): + return self.obs["low_dim_obs"] + + def pose(self): + return np.asarray(self.lo[21:25], dtype=np.float64) + + def waist(self): + return np.asarray(self.lo[:3], dtype=np.float64) + + def w2p(self, pw): + x, y, z, yaw = self.pose() + c, s = np.cos(yaw), np.sin(yaw) + d = np.asarray(pw[:2], float) - [x, y] + return np.array([c * d[0] + s * d[1], -s * d[0] + c * d[1]]) + + def p2w(self, pp): + x, y, z, yaw = self.pose() + 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]]) + + def hand_actual(self, side="right", tool=(0.10, 0, 0)): + qa = np.asarray(self.lo[3:10] if side == "left" else self.lo[12:19], float) + return g1fk.arm_fk(side, qa, self.waist(), tool=tool), qa + + def hand_world(self, tool=(0.10, 0, 0)): + T, _ = self.hand_actual(tool=tool) + return np.r_[self.p2w(T[:3, 3]), T[2, 3] + self.pose()[2]] + + def ik_world(self, pw, zw, R_w, q0=None, tool=(0.10, 0, 0), wrot=1.0): + pp = self.w2p(pw) + Rl = g1fk._rz(-self.pose()[3]) @ R_w + if q0 is None: + q0 = self.hand_actual()[1] + return g1fk.ik("right", np.array([pp[0], pp[1], zw - self.pose()[2]]), R=Rl, q0=q0, + waist=self.waist(), tool=tool, wrot=wrot) + + def hold(self, n): + for _ in range(n): + yield self.a + + def base_cmd(self, tx, ty, tyaw, vmax=0.25): + x, y, z, yaw = self.pose() + dx, dy = tx - x, ty - y + c, s = np.cos(yaw), np.sin(yaw) + bx, by = c * dx + s * dy, -s * dx + c * dy + v = np.array([bx, by]) * 2.0 + nv = np.linalg.norm(v) + if nv > vmax: + v *= vmax / nv + if np.linalg.norm(v) < 0.06: + v = v * 0 if np.hypot(bx, by) < 0.02 else v / max(np.linalg.norm(v), 1e-6) * 0.06 + self.a[0], self.a[1] = v + ey = wrap(tyaw - yaw) + w = np.clip(1.5 * ey, -0.5, 0.5) + if abs(w) < 0.08: + w = 0.0 if abs(ey) < 0.03 else np.sign(w) * 0.08 + self.a[3] = w + + def stop_base(self): + self.a[0] = self.a[1] = self.a[3] = 0.0 + + def go_to(self, tx, ty, tyaw, tol=0.025, ytol=0.05, maxn=300, vmax=0.25): + for i in range(maxn): + x, y, z, yaw = self.pose() + if np.hypot(tx - x, ty - y) < tol and abs(wrap(tyaw - yaw)) < ytol: + break + self.base_cmd(tx, ty, tyaw, vmax=vmax) + yield self.a + self.stop_base() + yield from self.hold(15) + + def _idle(self): + while True: + yield self.a + + # ------------------------------------------------------------------ door + def servo_grasp_door(self, h, th, zt=0.69, vgoal=62, maxit=14, k0=-0.03, dk=0.02, nstep=12): + n = np.array([np.cos(th), np.sin(th)]) + t = np.array([-np.sin(th), np.cos(th)]) + Rw = g1fk._rz(th) + self.a[20] = 0.0 + q, e = self.ik_world(h - 0.08 * n, zt, Rw) + self.a[12:19] = q + yield from self.hold(30) + k = k0 + lat = 0.0 + for it in range(maxit): + q, e = self.ik_world(h + k * n + lat * t, zt, Rw, q0=q) + self.a[12:19] = q + yield from self.hold(nstep) + hb = vision.handle_blob(self.tools.image("right_wrist")) + if hb is None: + k += dk + continue + u, vb, npx = hb + lat += -0.0015 * (u - 39) + if vb >= vgoal: + break + k += dk + yield from self.hold(10) + self.a[20] = 1.0 + yield from self.hold(35) + g = self.lo[51] + log(" grasp k", round(k, 3), "lat", round(lat, 3), "grip", round(float(g), 2), "t", self.obs["t"]) + self.info["door_grip_ok"] = g < 0.97 + + def admit_pull(self, v=0.08, n=300, xmin=0.17, zt=0.69, lat=0.5): + T, qa = self.hand_actual() + tgt = T[:3, 3].copy() + psi = np.arctan2(T[1, 0], T[0, 0]) + for i in range(n): + T, qa = self.hand_actual() + psi_a = np.arctan2(T[1, 0], T[0, 0]) + psi = psi + 0.5 * (psi_a - psi) + pd = -np.array([np.cos(psi), np.sin(psi), 0.0]) + err = T[:3, 3] - tgt + err -= pd * np.dot(err, pd) + tgt = tgt + pd * v * 0.02 + lat * err + tgt[2] = zt - self.pose()[2] + q, e = g1fk.ik("right", tgt, R=g1fk._rz(psi), q0=qa, waist=self.waist(), wrot=1.0) + self.a[12:19] = q + yield self.a + if T[0, 3] < xmin or self.lo[51] > 0.97: + break + + def door_stage(self, h): + th = door_theta(h) + st = h - g1fk._rz(th)[:2, :2] @ REL + log("stage th", np.degrees(th).round(1), "station", st.round(3), "t", self.obs["t"]) + self.stop_base() + self.a[4] = 0.0 + self.a[2] = 0.74 + self.a[12:19] = TUCK_R + self.a[5:12] = TUCK_L + self.a[19:21] = 0.0 + yield from self.hold(15) + yield from self.go_to(st[0], st[1], th) + self.a[2] = 0.66 + yield from self.hold(40) + yield from self.servo_grasp_door(h, th) + if not self.info["door_grip_ok"]: + self.info["stage_result"] = None + return + yield from self.admit_pull() + T, qa = self.hand_actual() + hn = self.p2w(T[:3, 3]) + log(" released at", hn.round(3), "theta", np.degrees(door_theta(hn)).round(1), "t", self.obs["t"]) + self.a[20] = 0.0 + yield from self.hold(12) + th2 = door_theta(hn) + n2 = np.array([np.cos(th2), np.sin(th2)]) + q, e = self.ik_world(hn - 0.08 * n2, 0.72, g1fk._rz(th2)) + self.a[12:19] = q + yield from self.hold(20) + self.info["stage_result"] = hn + + def open_door(self): + h = HANDLE0.copy() + for k in range(8): + yield from self.door_stage(h) + hn = self.info["stage_result"] + if hn is None: + if np.degrees(door_theta(h)) > 95: + break # open enough to reach the shelf + continue # retry the same stage + h = hn + if np.degrees(door_theta(h)) > 108: + break + self.info["door_theta"] = np.degrees(door_theta(h)) + + # ------------------------------------------------------------------ pan + def to_pan_station(self, st=(0.31, 0.12)): + # pull the hand straight back to the body before tucking + pp = self.p2w([0.20, -0.22]) + q, e = self.ik_world(pp, self.pose()[2] + 0.05, g1fk._rz(self.pose()[3])) + self.a[12:19] = q + yield from self.hold(25) + self.a[12:19] = TUCK_R + self.a[2] = 0.74 + self.a[4] = 0.0 + self.a[20] = 0.0 + yield from self.hold(20) + x, y, z, yaw = self.pose() + # back away from the open door, then come in from the front + yield from self.go_to(-0.45, y, yaw, tol=0.05, ytol=0.3, maxn=300) + yield from self.go_to(-0.35, 0.10, 0.0, tol=0.04, ytol=0.08, maxn=300) + yield from self.go_to(0.05, 0.10, 0.0, tol=0.04, ytol=0.08, maxn=250) + yield from self.go_to(st[0], st[1], 0.0, maxn=250) + # squat and lean to look into the shelf + self.a[2] = 0.62 + self.a[4] = 0.5 + yield from self.hold(45) + log("pan station", self.pose().round(3), self.waist().round(3), "t", self.obs["t"]) + + def locate_handle(self): + im = self.tools.image("head") + P, W = self.pose(), self.waist() + res = vision.pan_in_head(im) + if res is None: + log("pan not found") + return None + (cu, cv), tip_px = res + zt = 0.645 + tip = camera.pixel_to_plane_z(tip_px[0], tip_px[1], zt, P, W) + ctr = camera.pixel_to_plane_z(cu, cv, zt, P, W) + log("pan px", (round(cu, 1), round(cv, 1)), "tip px", tip_px, "tip", tip.round(3), "ctr", ctr.round(3)) + # sanity: the handle must lie inside the shelf + if not (0.55 < tip[0] < 0.85 and -0.22 < tip[1] < 0.30): + return None + return tip, ctr + + def pan_grasp(self): + res = self.locate_handle() + if res is None: + tip, ctr = np.array([0.665, -0.05, 0.645]), np.array([0.65, 0.09, 0.645]) + else: + tip, ctr = res + self.info["tip"], self.info["ctr"] = tip, ctr + gz = GRASP_Z + g = np.array([tip[0] + GRASP_DX, tip[1] + GRASP_DY]) + # the hand comes in diagonally (like the demonstration) so the forearm + # stays clear of the cabinet side wall; the handle crosses the fingers + d = np.array([np.cos(GRASP_YAW), np.sin(GRASP_YAW)]) + R = g1fk._rz(GRASP_YAW) + self.R_hold = R + self.a[20] = 0.0 + self.corr = np.zeros(3) + # Cartesian path from the tucked hand: up in front of the body, to the + # shelf opening, then diagonally in behind the handle tip + # stand up (in the squat the tucked hand is trapped by the thigh) and + # unfold the arm forward in joint space + self.a[2] = 0.74 + self.a[4] = 0.0 + yield from self.hold(35) + self.a[12:19] = UNFOLD + yield from self.hold(35) + w1 = np.array([0.50, 0.0, 0.80]) + yield from self.move_hand(w1, 40, R, settle=10, gain=0.0) + log("w1", self.hand_world().round(3), "target", w1.round(3)) + for i in range(50): + s = min(1.0, (i + 1) / 40) + self.a[2] = 0.74 - s * 0.12 + self.a[4] = s * 0.5 + q, e = self.ik_world(w1[:2], w1[2] - 0.12 * s, R) + self.a[12:19] = q + yield self.a + log("w1 squat", self.hand_world().round(3)) + p0 = g - 0.17 * d + yield from self.move_hand(np.r_[p0, gz + 0.04], 40, R, settle=10) + log("pre0", self.hand_world().round(3), "target", np.round(np.r_[p0, gz + 0.04], 3)) + yield from self.move_hand(np.r_[g - 0.10 * d, gz], 30, R, settle=10) + log("pre1", self.hand_world().round(3)) + for s in np.arange(-0.08, 0.0001, 0.02): + npx, u, v = vision.tan_blob(self.tools.image("right_wrist")) + log(" adv", round(s, 3), "tan", npx, round(u, 1), round(v, 1), "hand", self.hand_world().round(3)) + yield from self.move_hand(np.r_[g + s * d, gz], 8, R, settle=4) + yield from self.move_hand(np.r_[g, gz], 1, R, settle=15) + log("grasp hand", self.hand_world().round(3), "target", np.round(np.r_[g, gz], 3)) + self.a[20] = 1.0 + yield from self.hold(35) + self.info["pan_grip"] = float(self.lo[51]) + log("pan grip", self.info["pan_grip"], "t", self.obs["t"]) + + def move_hand(self, target, n, R_w, settle=0, gain=0.5, cmax=0.06): + """Move the right tool point linearly to a world target over n steps, + integrating a correction for gravity sag / tracking error.""" + target = np.asarray(target, float) + start = self.hand_world() + q = self.hand_actual()[1] + for i in range(n + settle): + s = min(1.0, (i + 1) / n) + wp = start + s * (target - start) + if i % 5 == 4: + err = wp - self.hand_world() + self.corr = np.clip(self.corr + gain * 0.2 * err, -cmax, cmax) + cmd = wp + self.corr + q, e = self.ik_world(cmd[:2], cmd[2], R_w, q0=q) + self.a[12:19] = q + yield self.a + + def carry_to_hob(self): + hw = self.hand_world() + # slide the pan out of the shelf + yield from self.move_hand([hw[0] - SLIDE, hw[1], hw[2] + 0.01], 45, self.R_hold, settle=10) + log("slid", self.hand_world().round(3), "grip", round(float(self.lo[51]), 2), "t", self.obs["t"]) + # stand up and straighten while holding the hand still in the world + hw = self.hand_world() + for i in range(40): + s = (i + 1) / 40 + self.a[2] = 0.62 + s * (0.74 - 0.62) + self.a[4] = 0.5 + s * (CARRY_PITCH - 0.5) + q, e = self.ik_world((hw + self.corr)[:2], (hw + self.corr)[2] + 0.05 * s, self.R_hold) + self.a[12:19] = q + yield self.a + # lift above the counter, then reach over the hob + hw = self.hand_world() + yield from self.move_hand([hw[0], hw[1], LIFT_Z], 45, self.R_hold, settle=10) + log("lifted", self.hand_world().round(3), "t", self.obs["t"]) + yield from self.move_hand([HOB_X, hw[1], LIFT_Z], 45, self.R_hold, settle=10) + log("over hob", self.hand_world().round(3), "grip", round(float(self.lo[51]), 2), "t", self.obs["t"]) + # lower until the pan rests on the hob + target = self.hand_world() + z = target[2] + zs = [] + for i in range(50): + z -= 0.006 + target[2] = z + yield from self.move_hand(target, 3, self.R_hold, gain=0.0) + zs.append(self.hand_world()[2]) + # contact: the hand stopped descending while the command kept going down + if len(zs) > 8 and zs[-9] - zs[-1] < 0.008: + break + log("contact", self.hand_world().round(3), "cmd z", round(z, 3), "t", self.obs["t"]) + self.a[20] = 0.0 + yield from self.hold(30) + hw = self.hand_world() + yield from self.move_hand([hw[0] - 0.12, hw[1] - 0.02, hw[2] + 0.04], 30, self.R_hold, settle=10) + self.a[12:19] = TUCK_R + yield from self.hold(40) + log("released, t", self.obs["t"]) + + # ------------------------------------------------------------------ script + def _script(self): + self.a[:] = np.asarray(self.tools.hold_action(), dtype=np.float64) + self.a[12:19] = TUCK_R + self.a[5:12] = TUCK_L + yield from self.hold(10) + yield from self.open_door() + yield from self.to_pan_station() + yield from self.pan_grasp() + if self.info["pan_grip"] > 0.97: + return + yield from self.carry_to_hob() diff --git a/policies/saucepan_to_hob/opus-s3/vision.py b/policies/saucepan_to_hob/opus-s3/vision.py new file mode 100644 index 0000000000000000000000000000000000000000..774d03dc512a00a4908568b002b047c88ae3d6cc --- /dev/null +++ b/policies/saucepan_to_hob/opus-s3/vision.py @@ -0,0 +1,78 @@ +"""Image feature detectors used by the policy.""" +import cv2 +import numpy as np + + +def pan_in_head(rgb, vmin=2): + """Saucepan body centre and handle tip in the head image (pixel coordinates). + + The body is the saturated copper blob; the tip is the end of the longest + continuous run of pan-coloured pixels along a ray from the body centre. + Runs that leave the image (or reach the masked top rows, where the wooden + counter edge has the same colour) are rejected. + """ + hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV) + H, S, V = hsv[..., 0].astype(int), hsv[..., 1].astype(int), hsv[..., 2].astype(int) + # copper body (H~10, dark) and tan wooden handle (H~16, light); the gold + # counter edge (H>=20, very bright) is excluded + body = (H >= 4) & (H <= 13) & (S > 75) & (V > 60) & (V < 160) + handle = (H >= 13) & (H <= 19) & (S > 35) & (V > 140) & (V < 215) + orange = body | handle + orange[:vmin, :] = False + body[:vmin, :] = False + n, lab, st, cen = cv2.connectedComponentsWithStats(body.astype(np.uint8)) + if n < 2: + return None + k = 1 + int(np.argmax(st[1:, 4])) + if st[k, 4] < 20: + return None + vs, us = np.nonzero(lab == k) + cu, cv = us.mean(), vs.mean() + r = np.sqrt(len(us) / np.pi) + # the handle: farthest pan-coloured pixel connected to the body + grown = cv2.dilate(orange.astype(np.uint8), np.ones((3, 3), np.uint8)) + n2, lab2 = cv2.connectedComponents(grown, connectivity=8) + comp = np.bincount(lab2[vs, us]).argmax() + if comp == 0: + return None + v2, u2 = np.nonzero((lab2 == comp) & orange) + d = np.hypot(u2 - cu, v2 - cv) + m = int(np.argmax(d)) + if d[m] < r + 4: + return None + return (cu, cv), (float(u2[m]), float(v2[m])) + + +def tan_blob(rgb): + """Wooden saucepan handle pixels in a wrist image: (count, mean u, mean v).""" + hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV) + H, S, V = hsv[..., 0].astype(int), hsv[..., 1].astype(int), hsv[..., 2].astype(int) + m = (H >= 8) & (H <= 25) & (S > 60) & (V > 90) + vs, us = np.nonzero(m) + if len(us) == 0: + return 0, 41.5, 41.5 + return int(len(us)), float(us.mean()), float(vs.mean()) + + +def handle_blob(rgb): + """Find the dark-grey cabinet door handle in a wrist image. + + Returns (u_centre_of_bottom_part, v_bottom, n_pixels) or None. + """ + hsv = cv2.cvtColor(rgb, cv2.COLOR_RGB2HSV) + S, V = hsv[..., 1].astype(int), hsv[..., 2].astype(int) + m = ((S < 45) & (V > 60) & (V < 125)).astype(np.uint8) + n, lab, stats, cent = cv2.connectedComponentsWithStats(m, connectivity=8) + best = None + for k in range(1, n): + x, y, w, h, area = stats[k] + if area < 15 or h < 2 * w or area < 0.5 * w * h: + continue + if best is None or area > stats[best][4]: + best = k + if best is None: + return None + vs, us = np.nonzero(lab == best) + vb = vs.max() + sel = vs >= vb - 12 + return float(us[sel].mean()), float(vb), int(len(vs)) diff --git a/policies/stack_blocks/astra-s1/episodes.csv b/policies/stack_blocks/astra-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..6f268ef7f90b4e072cb218d538a88b3ca93f3f4b --- /dev/null +++ b/policies/stack_blocks/astra-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,8750,timeout,0 +620001,0,8750,timeout,0 +620002,0,8750,timeout,0 +620003,0,8750,timeout,0 +620004,0,8750,timeout,0 +620005,0,8750,timeout,0 +620006,0,8750,timeout,0 +620007,0,8750,timeout,0 +620008,0,8750,timeout,0 +620009,0,8750,timeout,0 +620010,0,8750,timeout,0 +620011,0,8750,timeout,0 +620012,0,8750,timeout,0 +620013,0,8750,timeout,0 +620014,0,8750,timeout,0 +620015,0,8750,timeout,0 +620016,0,8750,timeout,0 +620017,0,8750,timeout,0 +620018,0,8750,timeout,0 +620019,0,7543,terminated,0 +620020,0,8750,timeout,0 +620021,0,8750,timeout,0 +620022,0,8750,timeout,0 +620023,0,8750,timeout,0 +620024,0,8750,timeout,0 +620025,0,8750,timeout,0 +620026,0,8750,timeout,0 +620027,0,8750,timeout,0 +620028,0,8750,timeout,0 +620029,0,8750,timeout,0 +620030,0,8750,timeout,0 +620031,0,8750,timeout,0 +620032,0,8750,timeout,0 +620033,0,8750,timeout,0 +620034,0,8750,timeout,0 +620035,0,8750,timeout,0 +620036,0,8750,timeout,0 +620037,0,8750,timeout,0 +620038,0,4395,terminated,0 +620039,0,8750,timeout,0 +620040,0,8750,timeout,0 +620041,0,8750,timeout,0 +620042,0,8750,timeout,0 +620043,0,8750,timeout,0 +620044,0,8750,timeout,0 +620045,0,8750,timeout,0 +620046,0,8750,timeout,0 +620047,0,8750,timeout,0 +620048,0,8750,timeout,0 +620049,0,8750,timeout,0 +620050,0,8750,timeout,0 +620051,0,8750,timeout,0 +620052,0,8750,timeout,0 +620053,0,8750,timeout,0 +620054,0,8750,timeout,0 +620055,0,8750,timeout,0 +620056,0,8750,timeout,0 +620057,0,8750,timeout,0 +620058,0,8750,timeout,0 +620059,0,8750,timeout,0 +620060,0,8750,timeout,0 +620061,0,8750,timeout,0 +620062,0,8750,timeout,0 +620063,0,8750,timeout,0 +620064,0,8750,timeout,0 +620065,0,8750,timeout,0 +620066,0,8750,timeout,0 +620067,0,8750,timeout,0 +620068,0,8750,timeout,0 +620069,0,8750,timeout,0 +620070,0,8750,timeout,0 +620071,0,8750,timeout,0 +620072,0,8750,timeout,0 +620073,0,8750,timeout,0 +620074,0,8750,timeout,0 +620075,0,8750,timeout,0 +620076,0,8750,timeout,0 +620077,0,8750,timeout,0 +620078,0,8750,timeout,0 +620079,0,8750,timeout,0 +620080,0,8750,timeout,0 +620081,0,8750,timeout,0 +620082,0,8750,timeout,0 +620083,0,8750,timeout,0 +620084,0,8750,timeout,0 +620085,0,8750,timeout,0 +620086,0,8750,timeout,0 +620087,1,8019,success,0 +620088,0,8750,timeout,0 +620089,0,8750,timeout,0 +620090,0,8750,timeout,0 +620091,0,8750,timeout,0 +620092,0,8750,timeout,0 +620093,0,8750,timeout,0 +620094,0,8750,timeout,0 +620095,0,8750,timeout,0 +620096,0,8750,timeout,0 +620097,0,8750,timeout,0 +620098,0,8750,timeout,0 +620099,0,8750,timeout,0 diff --git a/policies/stack_blocks/astra-s1/policy.py b/policies/stack_blocks/astra-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..895533dae9d0b97eeccf86ebbd1604465d1e2d43 --- /dev/null +++ b/policies/stack_blocks/astra-s1/policy.py @@ -0,0 +1,190 @@ +"""Deterministic camera-guided block transfer and stacking controller. + +Colour segmentation supplies image feedback. Proprioception closes the walking +loop, and a finite-state controller sequences grasping, transport and placement. +All geometry, gains and waypoints are hand-specified; no learned model or replay +of demonstration data is used. +""" + +import numpy as np +import cv2 + +def blobs(im,color='red'): + r,g,b=[im[:,:,i].astype(float) for i in range(3)] + mask=((r>90)&(r>g*1.6)&(r>b*1.6)) if color=='red' else ((g>80)&(g>r*1.35)&(g>b*1.2)) + n,lab,stats,cent=cv2.connectedComponentsWithStats(mask.astype('uint8')) + return [(float(cent[i,0]),float(cent[i,1]),int(stats[i,4]),int(stats[i,2]),int(stats[i,3])) for i in range(1,n) if stats[i,4]>8] + +def pad(im): + r,g,b=[im[:,:,i].astype(float) for i in range(3)] + yy,xx=np.where((g>80)&(g>r*1.35)&(g>b*1.2)) + if len(xx)<8:return None + width=xx.max()-xx.min()+1 + return ((xx.min()+xx.max())/2., yy.max()-.375*width,len(xx),width,yy.max()-yy.min()+1) + +def red_peaks(im): + r,g,b=[im[:,:,i].astype(float) for i in range(3)] + mask=((r>90)&(r>g*1.6)&(r>b*1.6)).astype('uint8');mask[:8]=0 + dist=cv2.distanceTransform(mask,cv2.DIST_L2,3) + yy,xx=np.where((dist>=2)&(dist>=cv2.dilate(dist,np.ones((5,5),np.uint8))-.01)) + if not len(xx):return [] + pts=list(zip(xx.astype(float),yy.astype(float))) + first=min(pts,key=lambda p:p[1]);close=[p for p in pts if abs(p[1]-first[1])<=1 and abs(p[0]-first[0])<5] + held=(float(np.mean([p[0] for p in close])),float(np.mean([p[1] for p in close]))) + rest=[p for p in pts if np.hypot(p[0]-held[0],p[1]-held[1])>6 and p[1]>=held[1]-1] + if not rest:return [held] + other=min(rest,key=lambda p:p[1]);close=[p for p in rest if abs(p[1]-other[1])<=1 and abs(p[0]-other[0])<5] + return [held,(float(np.mean([p[0] for p in close])),float(np.mean([p[1] for p in close])))] + +def project_world(pixel,z,obs): + # Pinhole ray intersection with a horizontal support plane. + p=obs['low_dim_obs'][21:25];u=(pixel[0]-41.5)/65.;v=(pixel[1]-41.5)/65. + theta=np.pi/3 + ray=np.array([np.cos(theta)-v*np.sin(theta),-u,-np.sin(theta)-v*np.cos(theta)]) + local=ray*((z-(p[2]+.50))/ray[2]);local[0]+=.05 + c=np.cos(p[3]);ss=np.sin(p[3]) + return p[:2]+np.array([c*local[0]-ss*local[1],ss*local[0]+c*local[1]]) + +class Policy: + def reset(self,obs,tools): + self.a=np.zeros(21);self.a[2]=.74;self.a[5]=-.8;self.a[7]=.8;self.a[10]=.4;self.a[12]=-.8;self.a[14]=-.8;self.a[17]=.3 + self.sent=np.array(tools.hold_action());self.stage='prepick';self.start=0;self.stable=0;self.target=None;self.count=0;self.way=0 + def goto(self,obs,x,y,yaw): + p=obs['low_dim_obs'][21:25];e=np.array([x,y])-p[:2];c=np.cos(p[3]);s=np.sin(p[3]);v=np.array([c*e[0]+s*e[1],-s*e[0]+c*e[1]])*1.5;v=np.clip(v,-.55,.55) + if np.linalg.norm(e)<.018:v*=0 + elif np.linalg.norm(v)<.065:v*=.065/np.linalg.norm(v) + self.a[:2]=v;err=(yaw-p[3]+np.pi)%(2*np.pi)-np.pi;self.a[3]=np.clip(err*2,-.9,.9) + return np.linalg.norm(e)<.035 and abs(err)<.035 + def change(self,stage,t): + self.stage=stage;self.start=t;self.a[:2]=0;self.a[3]=0;self.stable=0 + def act(self,obs,tools): + t=obs['t'];a=self.a;dt=t-self.start + if self.stage=='prepick' and dt>=40: + bs=[b for b in blobs(tools.image('head')) if b[1]>8] + if bs: + b=min(bs,key=lambda b:b[0]);p=obs['low_dim_obs'][21:25] + self.pick_goal=(.22,float(np.clip(p[1]+(20-b[0])*.008,-.6,.45)),0) + self.change('approach',t) + elif self.stage=='approach': + if self.goto(obs,*self.pick_goal) or dt>260: + self.change('settle_pick',t);a[5:12]=[-.1,0,0,0,0,.4,0];a[19]=0;a[2]=.74;self.target=None + elif self.stage=='settle_pick' and dt>60:self.change('pick',t) + elif self.stage=='pick': + if t%10==0: + bs=blobs(tools.image('left_wrist')) + if bs: + b=min(bs,key=lambda b:(b[0]-42)**2+(b[1]-40)**2) if self.target is None else min(bs,key=lambda b:(b[0]-self.target[0])**2+(b[1]-self.target[1])**2) + self.target=b;ex=b[0]-42;ey=b[1]-40 + if abs(ex)<12 and abs(ey)<12 and b[2]<2800:a[2]=max(.58,a[2]-.003) + a[7]=np.clip(a[7]-.00065*ex,-.85,.85);a[5]=np.clip(a[5]+.00055*ey,-.4,.18) + if abs(ex)<6 and abs(ey)<6 and b[2]>2500:self.stable+=10 + else:self.stable=0 + if self.stable>=30: + self.pickpose=a[5:12].copy();self.pickheight=a[2];a[19]=1;self.change('close',t) + if dt>1300: + self.change('prepick',t);a[5]=-.8;a[7]=.8;a[2]=.74;self.target=None + elif self.stage=='close' and dt>60: + a[5]=-.8;a[7]=.8;a[2]=.74;self.change('lift',t) + elif self.stage=='lift' and dt>100: + rs=blobs(tools.image('left_wrist')) + if not rs or max(b[2] for b in rs)<350: + a[19]=0;self.change('prepick',t) + else:self.change('route',t);self.way=0 + elif self.stage=='route': + goals=[(0,.95,0),(1.98,.95,0),(2.04,.16,np.pi)] + if self.goto(obs,*goals[self.way]): + if self.way==0: + self.change('calib',t);self.pickpose[2]=-.2;a[5:12]=self.pickpose;a[2]=self.pickheight + else: + self.way+=1 + if self.way==3:self.change('place_wait',t) + elif self.stage=='calib' and dt>100: + rs=blobs(tools.image('head')) + if rs:self.anchor=max(rs,key=lambda b:b[2])[:2] + else:self.anchor=(28.,38.) + a[5]=-.8;a[7]=.8;a[2]=.74;self.change('calib_lift',t) + elif self.stage=='calib_lift' and dt>60:self.way=1;self.change('route',t) + elif self.stage=='place_wait' and dt>60: + self.change('align',t);self.align_last=None + elif self.stage=='align': + if dt%100==1: + im=tools.image('head');pg=pad(im);gs=[pg] if pg else [] + if self.count==2: + peaks=red_peaks(im) + if peaks:self.stack_world=project_world(peaks[0],.84,obs) + if gs: + green=max(gs,key=lambda b:b[2]);self.align_last=(self.anchor,green) + ex=self.anchor[0]-green[0];ey=self.anchor[1]+(.74-self.pickheight)*85-green[1]+3 + body=obs['low_dim_obs'][21:25] + if self.count==2:ey-=max(0,self.pickheight+.12+.06-.75)*70 + elif self.count==1:ey-=max(0,self.pickheight+.06+.02-.77)*70 + self.align_goal=(body[0]-np.clip(ey*.009,-.12,.12),body[1]-np.clip(ex*.010,-.25,.25),np.pi) + if abs(ex)<3. and abs(ey)<3.:self.stable+=1 + else:self.stable=0 + if self.stable>=1 or dt>=400: + self.change('lower',t);a[5:12]=self.pickpose;self.clearance=.06 if self.count==2 else .02 + desired=self.pickheight+self.count*.06+self.clearance + cap=.75 if self.count==2 else (.77 if self.count==1 else .78) + a[2]=min(cap,desired) + offset=(desired-a[2])/.45;a[5]-=offset;a[10]+=offset + if self.stage=='align' and hasattr(self,'align_goal'): + if dt%100<80:self.goto(obs,*self.align_goal) + else:a[:2]=0 + elif self.stage=='lower' and dt>145: + self.change('fine',t);self.fine_root=float(obs['low_dim_obs'][23]);self.fine_shoulder=float(obs['low_dim_obs'][3]) + elif self.stage=='fine': + if dt%10==0: + im=tools.image('head');pg=pad(im);rs=[b for b in blobs(im) if b[1]>8] + if (pg and rs) or (self.count==2 and rs and hasattr(self,'stack_world')): + if pg is None:pg=(32.,40.,0,14,11) + red=min(rs,key=lambda b:(b[0]-pg[0])**2+(b[1]-(pg[1]-5-6*self.count))**2) + ex=red[0]-pg[0];ey=red[1]-pg[1]+5+6*self.count + if self.count>0: + peaks=red_peaks(im) + if len(peaks)>1: + red=peaks[0];pg=peaks[1];ex=red[0]-pg[0];ey=red[1]-pg[1]+8+(4 if self.count==2 else 0) + elif peaks: + ex=0;ey=0 + da=np.clip(ex*.006,-.018,.018);ds=np.clip(-ey*.003,-.012,.012) + if self.count==2 and hasattr(self,'stack_world'): + peaks=red_peaks(im) + da=0.;ds=0. + if peaks: + red=peaks[0] + z=.94+float(obs['low_dim_obs'][23])-self.fine_root + now=project_world(red,z,obs);delta=self.stack_world-now + if dt%100==0: + body=obs['low_dim_obs'][21:25] + self.fine_goal=(body[0]+np.clip(delta[0],-.08,.08),body[1]+np.clip(delta[1],-.07,.07),np.pi) + ex=delta[1]*100;ey=delta[0]*100 + a[7]=np.clip(a[7]+da,-.7,.5) + a[5]+=ds;a[10]-=ds;a[2]=np.clip(a[2]+ds*.45,.56,.9) + self.align_last=(red,pg) + if abs(ex)<1.5 and abs(ey)<1.5:self.stable+=10 + else:self.stable=0 + if self.count==2 and hasattr(self,'fine_goal'): + if dt%100<70:self.goto(obs,*self.fine_goal) + else:a[:2]=0 + if self.stable>=30 or dt>=(300 if self.count==2 else 200): + a[2]-=(.04 if self.count==2 else self.clearance);self.change('touchdown',t) + elif self.stage=='touchdown' and dt>90: + a[19]=0;self.change('release',t) + elif self.stage=='release' and dt>60: + a[5]=-.8;a[2]=.74;self.change('retreat',t) + elif self.stage=='retreat' and dt>100: + self.count+=1;a[7]=.8 + if self.count==3:self.change('done',t) + else:self.way=0;self.change('return',t) + elif self.stage=='return': + goals=[(2.06,.95,np.pi),(0,.95,0),(.1,0,0)] + if self.goto(obs,*goals[self.way]): + self.way+=1 + if self.way==3:self.change('prepick',t);self.target=None + if self.stage in ['pick','close','settle_pick','prepick']: + a[3]=np.clip(-((obs['low_dim_obs'][24]+np.pi)%(2*np.pi)-np.pi)*2,-.3,.3) + if self.stage in ['align','lower','fine','touchdown','release','retreat','place_wait']: + a[3]=np.clip(((np.pi-obs['low_dim_obs'][24]+np.pi)%(2*np.pi)-np.pi)*2,-.3,.3) + # Bound target changes so a carried block is not jerked out of the fingers. + limits=np.array([.05,.05,.0015,.05,.012]+[.012]*14+[1.,1.]) + self.sent+=np.clip(a-self.sent,-limits,limits) + return self.sent.copy() diff --git a/policies/stack_blocks/astra-s2/episodes.csv b/policies/stack_blocks/astra-s2/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..a7e0c8f54ec55e2f7e63716f54da48656a6fb135 --- /dev/null +++ b/policies/stack_blocks/astra-s2/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,7659,terminated,0 +620001,0,8750,timeout,0 +620002,0,8750,timeout,0 +620003,0,8750,timeout,0 +620004,0,8750,timeout,0 +620005,0,8750,timeout,0 +620006,0,8750,timeout,0 +620007,0,8750,timeout,0 +620008,0,8750,timeout,0 +620009,0,8750,timeout,0 +620010,0,8750,timeout,0 +620011,0,8750,timeout,0 +620012,0,8750,timeout,0 +620013,0,8750,timeout,0 +620014,0,8750,timeout,0 +620015,0,8750,timeout,0 +620016,0,8750,timeout,0 +620017,0,8750,timeout,0 +620018,0,8750,timeout,0 +620019,0,8750,timeout,0 +620020,0,8750,timeout,0 +620021,0,8750,timeout,0 +620022,0,8750,timeout,0 +620023,0,8750,timeout,0 +620024,0,8750,timeout,0 +620025,0,8750,timeout,0 +620026,0,7728,terminated,0 +620027,0,8750,timeout,0 +620028,0,8750,timeout,0 +620029,0,8750,timeout,0 +620030,0,8750,timeout,0 +620031,0,8750,timeout,0 +620032,0,8750,timeout,0 +620033,0,8750,timeout,0 +620034,0,8750,timeout,0 +620035,0,8750,timeout,0 +620036,0,8750,timeout,0 +620037,0,8750,timeout,0 +620038,0,8750,timeout,0 +620039,1,8044,success,0 +620040,0,8750,timeout,0 +620041,0,8750,timeout,0 +620042,0,8750,timeout,0 +620043,0,8750,timeout,0 +620044,0,8750,timeout,0 +620045,0,8750,timeout,0 +620046,0,8750,timeout,0 +620047,0,8750,timeout,0 +620048,0,8750,timeout,0 +620049,0,8750,timeout,0 +620050,0,8750,timeout,0 +620051,0,8750,timeout,0 +620052,0,8750,timeout,0 +620053,0,8750,timeout,0 +620054,0,8750,timeout,0 +620055,0,7724,terminated,0 +620056,0,8750,timeout,0 +620057,0,8750,timeout,0 +620058,0,8750,timeout,0 +620059,0,8750,timeout,0 +620060,0,8750,timeout,0 +620061,0,8750,timeout,0 +620062,0,8750,timeout,0 +620063,0,8750,timeout,0 +620064,0,8750,timeout,0 +620065,0,8750,timeout,0 +620066,0,8750,timeout,0 +620067,0,8750,timeout,0 +620068,0,8750,timeout,0 +620069,0,8750,timeout,0 +620070,0,8750,timeout,0 +620071,0,1411,terminated,0 +620072,0,8750,timeout,0 +620073,0,8750,timeout,0 +620074,0,8750,timeout,0 +620075,0,8750,timeout,0 +620076,0,8750,timeout,0 +620077,0,8750,timeout,0 +620078,0,8750,timeout,0 +620079,0,8750,timeout,0 +620080,0,2189,terminated,0 +620081,0,7480,terminated,0 +620082,1,7549,success,0 +620083,0,8750,timeout,0 +620084,0,8750,timeout,0 +620085,0,8750,timeout,0 +620086,0,8750,timeout,0 +620087,0,8750,timeout,0 +620088,0,8750,timeout,0 +620089,0,8750,timeout,0 +620090,0,8750,timeout,0 +620091,0,8750,timeout,0 +620092,0,8750,timeout,0 +620093,0,8750,timeout,0 +620094,0,8750,timeout,0 +620095,0,8750,timeout,0 +620096,0,8750,timeout,0 +620097,0,8750,timeout,0 +620098,0,8750,timeout,0 +620099,0,8750,timeout,0 diff --git a/policies/stack_blocks/astra-s2/policy.py b/policies/stack_blocks/astra-s2/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..9103f27873673ee6340b20ca1ee0ead7d51b67b3 --- /dev/null +++ b/policies/stack_blocks/astra-s2/policy.py @@ -0,0 +1,182 @@ +"""Deterministic, camera-guided block transport and stacking controller. + +Colour segmentation drives grasp alignment. Pelvis feedback closes the walking +loop, and visible pad edges provide a reference when the hand occludes its centre. +No demonstration files or fitted models are used at runtime. +""" + +import numpy as np +import cv2 + +def red_blobs(im): + m=((im[:,:,0]>100)&(im[:,:,0]>im[:,:,1]*1.7)&(im[:,:,0]>im[:,:,2]*1.7)).astype(np.uint8) + n,l,s,c=cv2.connectedComponentsWithStats(m) + return [(c[i],int(s[i,4]),s[i,:4]) for i in range(1,n) if s[i,4]>15] + +def wrap(a):return (a+np.pi)%(2*np.pi)-np.pi + +def green_info(im): + g=(im[:,:,1]>100)&(im[:,:,1]>im[:,:,0]*1.25)&(im[:,:,1]>im[:,:,2]*1.15) + vv,uu=np.where(g) + if len(uu)<8:return None + return np.array([(uu.min()+uu.max())/2,(vv.min()+vv.max())/2]),float(uu.max()-uu.min()+1) + +def tops(im): + m=((im[:,:,0]>230)&(im[:,:,1]<60)&(im[:,:,2]<60)).astype(np.uint8) + n,l,s,c=cv2.connectedComponentsWithStats(m) + return [(c[i],s[i,4],s[i,:4]) for i in range(1,n) if s[i,4]>8] + +class Policy: + def reset(self,obs,tools): + self.a=np.array(tools.hold_action());self.a[19:]=0;self.a[12]=-.3 + self.state='source_align';self.start=0;self.count=0;self.good=0;self.target_y=0.;self.retries=0 + self.last_uv=np.array([30.,35.]);self.placed=[] + def change(self,s,obs): + self.state=s;self.start=obs['t'];self.good=0;self.a[0:2]=0;self.a[3]=0 + def route(self,points,nextstate,obs): + self.points=list(points);self.nextstate=nextstate;self.change('route',obs) + def pad(self,im): + g=(im[:,:,1]>100)&(im[:,:,1]>im[:,:,0]*1.25)&(im[:,:,1]>im[:,:,2]*1.15) + vv,uu=np.where(g) + if len(uu)<8:return None + w=float(uu.max()-uu.min()+1) + self.pad_width=max(self.pad_width,w) + pw=self.pad_width + if w<.8*pw: + u=uu.max()-(pw-1)/2 if uu.mean()>self.held_uv[0] else uu.min()+(pw-1)/2 + else:u=(uu.max()+uu.min())/2 + return np.array([u,vv.max()-.43*pw]),pw + def drive(self,obs,target): + x,y,z,yaw=obs['low_dim_obs'][21:25];tx,ty,th=target + err=np.array([tx-x,ty-y]);dist=np.linalg.norm(err) + v=np.clip(err*1.8,-.45,.45) + if dist>.027 and np.linalg.norm(v)<.07:v*=.07/max(np.linalg.norm(v),1e-6) + if dist<.027:v[:]=0 + 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(wrap(th-yaw)*2,-.75,.75) + return dist<.035 and abs(wrap(th-yaw))<.045 + def act(self,obs,tools): + a=self.a;t=obs['t'];dt=t-self.start;p=obs['low_dim_obs'];x,y,z,yaw=p[21:25] + if self.state=='route': + if self.drive(obs,self.points[0]): + self.points.pop(0) + if not self.points:self.change(self.nextstate,obs) + elif self.state=='source_align': + a[5]=0;a[7]=.12;a[19]=0 + a[3]=np.clip(-wrap(yaw)*2,-.3,.3) + if dt%20==0: + bs=red_blobs(tools.image('head')) + if bs: + u,v=min(bs,key=lambda b:b[0][0])[0] + self.target_y=y+(14-u)*.009 + err=self.target_y-y + a[1]=np.clip(err*1.5,-.18,.18) if abs(err)>.025 else 0 + if 0100 and abs(err)<.025 or dt>450: + self.change('pregrasp',obs) + elif self.state=='pregrasp': + if dt>60:self.change('grasp',obs);self.last_uv=np.array([42.,35.]);self.stopped=False + elif self.state=='grasp': + a[3]=np.clip(-wrap(yaw)*1.5,-.3,.3) + if dt%10==0: + bs=red_blobs(tools.image('left_wrist')) + if bs: + b=min(bs,key=lambda b:np.linalg.norm(b[0]-self.last_uv));(u,v),area,box=b + self.last_uv=np.array([u,v]) + a[7]=np.clip(a[7]+np.clip((42-u)*.0015,-.035,.035),-.8,.65) + a[5]=np.clip(a[5]+np.clip((v-43)*.0012,-.028,.028),-.2,.36) + a[0]=.07 if area<2600 and not self.stopped else 0 + if area>=2600:self.stopped=True + if self.stopped and abs(u-42)<4 and abs(v-43)<4:self.good+=10 + else:self.good=0 + else:a[0]=0 + if self.good>=50 or dt>600: + self.pick_angles=a[[5,7]].copy();self.change('close',obs) + elif self.state=='close': + a[19]=1 + if dt>50:self.change('lift',obs);a[5]=-.25 + elif self.state=='lift': + if dt>70: + bs=red_blobs(tools.image('left_wrist')) + if bs and max(b[1] for b in bs)>1000: + self.retries=0 + self.route([(0.,y,0),(0.,-.95,0),(2.12,-.95,0),(2.12,0.,np.pi)],'place_start',obs) + else: + self.retries+=1;a[19]=0;a[[5,7]]=self.pick_angles + self.change('pregrasp',obs) + elif self.state=='place_start': + if dt==1: + im=tools.image('head');g=green_info(im);bs=tops(im) + self.support_offset=np.zeros(2) + if self.count and g and bs: + b=min(bs,key=lambda b:np.linalg.norm(b[0]-g[0])) + self.support_offset=(b[0]-g[0])/g[1] + a[5]=-.45;a[7]=-.35 + if dt>60:self.change('place_lower',obs) + elif self.state=='place_lower': + a[5]=self.pick_angles[0]-.05-.16*self.count + if dt>70: + im=tools.image('head');bs=tops(im);g=green_info(im) + # The carried face is nearer the head camera than the support. + # Its horizontal ordering can change as the tower grows. + if bs:self.held_uv=max(bs,key=lambda b:b[1])[0].copy() + else:self.held_uv=np.array([34.,38.-7*self.count]) + self.pad_width=g[1] if g else 12. + g=self.pad(im) + if self.count and g and bs: + supports=[b for b in bs if np.linalg.norm(b[0]-self.held_uv)>4] + if supports: + b=min(supports,key=lambda b:b[0][1]) + self.support_offset=(b[0]-g[0])/g[1] + self.change('place_align',obs) + elif self.state=='place_align': + if dt%20==0: + im=tools.image('head');g=self.pad(im);bs=tops(im) + if bs: + b=min(bs,key=lambda b:np.linalg.norm(b[0]-self.held_uv)) + if np.linalg.norm(b[0]-self.held_uv)<8:self.held_uv=b[0].copy() + if g: + gp,gw=g + desired=self.held_uv-self.support_offset*gw+np.array([.16*gw,(.30+.07*self.count)*gw]) + err=desired-gp + a[0]=.065 if err[1]>1.3 else (-.065 if err[1]<-1.3 else 0) + a[1]=-.065 if err[0]<-1.3 else (.065 if err[0]>1.3 else 0) + a[3]=np.clip(wrap(np.pi-yaw)*1.5,-.3,.3) + if np.max(np.abs(err))<2:self.good+=20 + else:self.good=0 + else:a[0:2]=0 + if self.good>=60 or dt>240:self.change('place_fine',obs) + elif self.state=='place_fine': + a[0:2]=0 + if dt>=50 and dt%60<10 and hasattr(self,'fine_v'):a[0]=self.fine_v + if dt>=50 and dt%60==50: + im=tools.image('head');g=self.pad(im);bs=tops(im) + if g and bs: + b=min(bs,key=lambda b:np.linalg.norm(b[0]-self.held_uv)) + self.held_uv=b[0].copy();gp,gw=g + goal=gp+self.support_offset*gw-np.array([.16*gw,(.30+.07*self.count)*gw]) + err=self.held_uv-goal + a[7]+=np.clip(err[0]*.012,-.09,.09) + self.fine_v=.065*np.sign(err[1]) if abs(err[1])>1.2 else 0 + if np.max(np.abs(err))<1.5:self.good+=1 + else:self.good=0 + if dt>230 or self.good>=2:self.change('place_settle',obs) + elif self.state=='place_settle': + if dt>50: + if not self.count: + self.drop_pose=(x,y,yaw);self.drop_angles=a[[5,7]].copy() + self.change('release',obs) + elif self.state=='release': + a[19]=max(0.,1.-dt/65.) + if dt>85:a[5]=-.45;self.change('withdraw',obs) + elif self.state=='withdraw': + if dt>50: + a[7]=.12 + self.count+=1 + if self.count>=3:self.change('done',obs) + else:self.route([(2.18,y,np.pi),(2.18,-.95,np.pi),(0.08,-.95,0),(0.08,0,0)],'source_align',obs) + # Keep the hand over the destination table during visual corrections. + if self.state in ('place_align','place_fine'): + if x>2.12 and a[0]<0:a[0]=0 + if x<1.80 and a[0]>0:a[0]=0 + return a.copy() diff --git a/policies/stack_blocks/astra-s3/episodes.csv b/policies/stack_blocks/astra-s3/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..8fcb0c0512881a9b4217d02836043a165aaa5b33 --- /dev/null +++ b/policies/stack_blocks/astra-s3/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,6937,terminated,0 +620001,0,8750,timeout,0 +620002,0,7358,terminated,0 +620003,0,7565,terminated,0 +620004,0,7556,terminated,0 +620005,0,8750,timeout,0 +620006,0,8750,timeout,0 +620007,0,1378,terminated,0 +620008,0,8750,timeout,0 +620009,0,1571,terminated,0 +620010,0,7557,terminated,0 +620011,0,7541,terminated,0 +620012,0,7555,terminated,0 +620013,0,8750,timeout,0 +620014,0,7017,terminated,0 +620015,0,1972,terminated,0 +620016,0,8750,timeout,0 +620017,0,8750,timeout,0 +620018,0,8750,timeout,0 +620019,0,1459,terminated,0 +620020,0,8750,timeout,0 +620021,0,8750,timeout,0 +620022,0,7007,terminated,0 +620023,0,7319,terminated,0 +620024,0,6953,terminated,0 +620025,0,8750,timeout,0 +620026,0,8750,timeout,0 +620027,0,8750,timeout,0 +620028,0,7569,terminated,0 +620029,0,6992,terminated,0 +620030,0,6931,terminated,0 +620031,0,8750,timeout,0 +620032,0,7575,terminated,0 +620033,0,8750,timeout,0 +620034,0,1185,terminated,0 +620035,0,6976,terminated,0 +620036,0,8750,timeout,0 +620037,0,6743,terminated,0 +620038,0,8007,terminated,0 +620039,0,8750,timeout,0 +620040,0,7405,terminated,0 +620041,0,1006,terminated,0 +620042,0,6904,terminated,0 +620043,0,8750,timeout,0 +620044,0,7002,terminated,0 +620045,0,8750,timeout,0 +620046,0,8750,timeout,0 +620047,0,6943,terminated,0 +620048,0,8206,terminated,0 +620049,0,8750,timeout,0 +620050,0,8750,timeout,0 +620051,0,6902,terminated,0 +620052,0,8750,timeout,0 +620053,0,8750,timeout,0 +620054,0,8750,timeout,0 +620055,0,8750,timeout,0 +620056,0,8750,timeout,0 +620057,0,7389,terminated,0 +620058,0,2068,terminated,0 +620059,0,8750,timeout,0 +620060,0,1184,terminated,0 +620061,0,8750,timeout,0 +620062,0,6761,terminated,0 +620063,0,6972,terminated,0 +620064,0,6800,terminated,0 +620065,0,8750,timeout,0 +620066,0,8750,timeout,0 +620067,0,6973,terminated,0 +620068,0,7557,terminated,0 +620069,0,7346,terminated,0 +620070,0,7613,terminated,0 +620071,0,8750,timeout,0 +620072,0,7562,terminated,0 +620073,0,1614,terminated,0 +620074,0,8750,timeout,0 +620075,0,8750,timeout,0 +620076,0,8750,timeout,0 +620077,0,7008,terminated,0 +620078,0,8750,timeout,0 +620079,0,8750,timeout,0 +620080,0,8750,timeout,0 +620081,0,1566,terminated,0 +620082,0,6937,terminated,0 +620083,0,8750,timeout,0 +620084,0,6748,terminated,0 +620085,0,8750,timeout,0 +620086,0,2214,terminated,0 +620087,0,8750,timeout,0 +620088,0,8750,timeout,0 +620089,0,1423,terminated,0 +620090,0,8750,timeout,0 +620091,0,6768,terminated,0 +620092,0,7349,terminated,0 +620093,0,8750,timeout,0 +620094,0,6931,terminated,0 +620095,0,1950,terminated,0 +620096,0,8750,timeout,0 +620097,0,8750,timeout,0 +620098,0,6956,terminated,0 +620099,0,8750,timeout,0 diff --git a/policies/stack_blocks/astra-s3/policy.py b/policies/stack_blocks/astra-s3/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..dd8b78169496dfa669eda4b241b3308b299cdaee --- /dev/null +++ b/policies/stack_blocks/astra-s3/policy.py @@ -0,0 +1,182 @@ +"""Deterministic visual grasping, closed-loop walking, and block placement.""" +import numpy as np +import cv2 + +def blobs(im, color='red'): + r, g, b = [im[:, :, k].astype(float) for k in range(3)] + m = (r > 90) & (r > g * 1.7) & (r > b * 1.7) if color == 'red' else (g > 80) & (g > r * 1.3) & (g > b * 1.2) + n, l, st, ct = cv2.connectedComponentsWithStats(m.astype('uint8')) + return sorted([(int(st[i, 4]), *ct[i], *st[i, :4]) for i in range(1, n) if st[i, 4] >= 5], reverse=True) + +class Policy: + + def reset(self, obs, tools): + self.o = obs + self.tools = tools + self.a = np.array(tools.hold_action(), float) + self.gen = self.run() + self.stage = 'start' + + def act(self, obs, tools): + self.o = obs + self.tools = tools + try: + next(self.gen) + except StopIteration: + pass + return self.a.copy() + + def pose(self, changes, n=80): + old = self.a.copy() + goal = old.copy() + for k, v in changes.items(): + goal[k] = v + for i in range(n): + f = min(1, (i + 1) / max(1, n - 25)) + f = f * f * (3 - 2 * f) + self.a = old * (1 - f) + goal * f + yield + + def wait(self, n): + for _ in range(n): + yield + + def goto(self, target): + self.a[2] = 0.74 + self.a[4] = 0 + for i in range(900): + p = self.o['low_dim_obs'][21:25] + d = np.array(target[:2]) - p[:2] + th = (target[2] - p[3] + np.pi) % (2 * np.pi) - np.pi + c, s = (np.cos(p[3]), np.sin(p[3])) + bd = np.array([c * d[0] + s * d[1], -s * d[0] + c * d[1]]) + v = np.clip(bd * 1.8, -0.34, 0.34) + if np.linalg.norm(v) < 0.065 and np.linalg.norm(d) > 0.012: + v *= 0.065 / max(np.linalg.norm(v), 1e-08) + if np.linalg.norm(d) < 0.012: + v *= 0 + self.a[:2] = v + self.a[3] = np.clip(th * 2, -0.5, 0.5) + if np.linalg.norm(d) < 0.012 and abs(th) < 0.018: + break + yield + self.a[:2] = 0 + self.a[3] = 0 + yield from self.wait(35) + + def pickup(self, sides): + self.stage = 'pickup' + self.lateral = {side: self.a[6 + 7 * side] for side in sides} + for side in sides: + self.a[19 + side] = 0 + for i in range(360): + if i % 5 == 0: + for side in sides: + p = 5 + 7 * side + rr = p + 1 + cam = ['left_wrist', 'right_wrist'][side] + bs = blobs(self.tools.image(cam)) + if bs: + ar, x, y, bx, by, w, h = bs[0] + self.lateral[side] += np.clip(0.001 * (42 - x), -0.015, 0.015) + lr = self.lateral[side] + if side == 1 and lr > 0 or (side == 0 and lr < 0): + self.a[rr] = 0 + self.a[p + 2] = lr * 1.8 + else: + self.a[rr] = lr + self.a[p + 2] = 0 + self.a[p] += np.clip(0.001 * (y - 32), -0.012, 0.012) + self.a[rr] = np.clip(self.a[rr], -0.5, 0.5) + self.a[p] = np.clip(self.a[p], -0.5, 0.6) + self.a[2] = max(0.67, self.a[2] - 0.0003) + yield + yield from self.pose({19 + s: 1 for s in sides}, 45) + yield from self.pose({2: 0.74, 5: -0.25, 12: -0.25}, 100) + + def acquire(self, sides): + yield from self.pickup(sides) + missing = [] + for side in sides: + bs = blobs(self.tools.image(['left_wrist', 'right_wrist'][side])) + if not bs or bs[0][0] < 1200: + missing.append(side) + if missing: + changes = {2: 0.74, 5: -0.6, 12: -0.6} + for side in missing: + p = 5 + 7 * side + changes.update({p: 0, p + 1: 0, p + 2: 0, 19 + side: 0}) + yield from self.pose(changes, 90) + yield from self.pickup(missing) + + def place(self, side, level): + self.stage = 'place_' + str(level) + yield from self.pose({6: 0.2, 13: -0.2, 7: 0, 14: 0, 5: -0.6 if level > 0 else self.a[5], 12: -0.6 if level > 0 else self.a[12]}, 110) + yield from self.goto([(2.17 if level == 2 else 2.02) if side else 2.02, -0.25 if side else 0.08, np.pi]) + p = 5 + side * 7 + other = 12 if side == 0 else 5 + ht = [0.69, 0.78, 0.79][level] + sh = -0.32 if level < 2 else -0.66 + yield from self.pose({2: ht, 4: 0.28, p: sh, other: -0.63}, 110) + yield from self.wait(30) + if level > 0: + self.stage = 'align_' + str(level) + for i in range(150): + if i % 5 == 0: + bs = blobs(self.tools.image('head')) + bs = [b for b in bs if b[0] > 25] + if len(bs) >= 2: + held = min(bs, key=lambda b: (b[1] - (12 if side == 0 else 72)) ** 2 + (b[2] - 8) ** 2) + rem = [b for b in bs if b is not held] + support = min(rem, key=lambda b: abs(b[1] - held[1]) + abs(b[2] - 30)) + ar, x, y, bx, by, w, h = held + sr, sx, sy, sbx, sby, sw, shh = support + if level == 2: + sy = sby + shh * 0.27 + sr = sr * 0.52 + ratio = 1.22 + vp = 42 + 60 / np.tan(0.87 + float(self.o['low_dim_obs'][2])) + tx = 42 + ratio * (sx - 42) + ty = vp + ratio * (sy - vp) + ex = x - tx + ey = y - ty + self.a[p + 1] = np.clip(self.a[p + 1] + np.clip(ex * 0.003, -0.012, 0.012), -0.6, 0.6) + self.a[4] = np.clip(self.a[4] + np.clip(ey * 0.001, -0.008, 0.008), 0.1, 0.45) + self.a[p] = sh - (self.a[4] - 0.28) + yield + yield from self.pose({19 + side: 0}, 35) + yield from self.pose({2: 0.74, 4: 0, p: -0.7, other: -0.25 if level == 0 else -0.7}, 110) + + def run(self): + yield from self.pose({19: 0, 20: 0}, 30) + self.stage = 'approach' + yield from self.goto([0.22, 0, 0]) + yield from self.acquire([0, 1]) + self.stage = 'transport' + for t in [[-0.05, -0.95, 0], [2.2, -0.95, 0], [2.1, -0.25, np.pi]]: + yield from self.goto(t) + yield from self.place(1, 0) + yield from self.place(0, 1) + self.stage = 'return' + yield from self.goto([2.3, float(self.o['low_dim_obs'][22]), np.pi]) + for t in [[2.2, -0.95, np.pi], [-0.05, -0.95, np.pi], [0.22, 0.18, 0]]: + yield from self.goto(t) + yield from self.pose({5: -0.5, 6: 0, 12: -0.5, 13: 0, 7: 0, 14: 0}, 80) + for _ in range(4): + bs = blobs(self.tools.image('head')) + if not bs: + break + ar, x, y, *_ = bs[0] + if abs(x - 62) < 3: + break + pos = self.o['low_dim_obs'][21:25] + yield from self.goto([0.22, float(pos[1]) + np.clip((62 - x) * 0.007, -0.25, 0.25), 0]) + yield from self.pose({5: 0, 6: 0, 12: 0, 13: 0, 7: 0, 14: 0}, 100) + yield from self.acquire([1]) + self.stage = 'transport_last' + yield from self.pose({12: -0.6, 5: -0.7}, 100) + for t in [[-0.05, -0.95, 0], [2.2, -0.95, 0], [2.1, -0.25, np.pi]]: + yield from self.goto(t) + yield from self.place(1, 2) + self.stage = 'finish' + yield from self.wait(100) diff --git a/policies/stack_blocks/deepseek1017-s1/episodes.csv b/policies/stack_blocks/deepseek1017-s1/episodes.csv new file mode 100644 index 0000000000000000000000000000000000000000..393503e1eedb9f98a7cb9b142b76c73cf253607a --- /dev/null +++ b/policies/stack_blocks/deepseek1017-s1/episodes.csv @@ -0,0 +1,101 @@ +seed,success,length,termination,fell +620000,0,1762,terminated,0 +620001,0,1860,terminated,0 +620002,0,1607,terminated,0 +620003,0,1615,terminated,0 +620004,0,1871,terminated,0 +620005,0,8750,timeout,0 +620006,0,1742,terminated,0 +620007,0,1745,terminated,0 +620008,0,1750,terminated,0 +620009,0,8750,timeout,0 +620010,0,8750,timeout,0 +620011,0,8750,timeout,0 +620012,0,1752,terminated,0 +620013,0,1865,terminated,0 +620014,0,1610,terminated,0 +620015,0,8750,timeout,0 +620016,0,8750,timeout,0 +620017,0,8750,timeout,0 +620018,0,1803,terminated,0 +620019,0,1876,terminated,0 +620020,0,1867,terminated,0 +620021,0,8750,timeout,0 +620022,0,8750,timeout,0 +620023,0,1608,terminated,0 +620024,0,1739,terminated,0 +620025,0,1754,terminated,0 +620026,0,8750,timeout,0 +620027,0,1710,terminated,0 +620028,0,306,terminated,0 +620029,0,1866,terminated,0 +620030,0,948,terminated,0 +620031,0,1874,terminated,0 +620032,0,8750,timeout,0 +620033,0,1734,terminated,0 +620034,0,1610,terminated,0 +620035,0,1864,terminated,0 +620036,0,8750,timeout,0 +620037,0,8750,timeout,0 +620038,0,1868,terminated,0 +620039,0,360,terminated,0 +620040,0,1727,terminated,0 +620041,0,8750,timeout,0 +620042,0,8750,timeout,0 +620043,0,1770,terminated,0 +620044,0,1863,terminated,0 +620045,0,487,terminated,0 +620046,0,1038,terminated,0 +620047,0,1655,terminated,0 +620048,0,1740,terminated,0 +620049,0,1752,terminated,0 +620050,0,8750,timeout,0 +620051,0,1753,terminated,0 +620052,0,1742,terminated,0 +620053,0,8750,timeout,0 +620054,0,1358,terminated,0 +620055,0,8750,timeout,0 +620056,0,1601,terminated,0 +620057,0,1606,terminated,0 +620058,0,1776,terminated,0 +620059,0,8750,timeout,0 +620060,0,8750,timeout,0 +620061,0,1761,terminated,0 +620062,0,382,terminated,0 +620063,0,1865,terminated,0 +620064,0,1853,terminated,0 +620065,0,8750,timeout,0 +620066,0,1009,terminated,0 +620067,0,1866,terminated,0 +620068,0,1644,terminated,0 +620069,0,8750,timeout,0 +620070,0,1869,terminated,0 +620071,0,437,terminated,0 +620072,0,8750,timeout,0 +620073,0,1868,terminated,0 +620074,0,1624,terminated,0 +620075,0,8750,timeout,0 +620076,0,1746,terminated,0 +620077,0,1737,terminated,0 +620078,0,8750,timeout,0 +620079,0,8750,timeout,0 +620080,0,1867,terminated,0 +620081,0,8750,timeout,0 +620082,0,1773,terminated,0 +620083,0,227,terminated,0 +620084,0,8750,timeout,0 +620085,0,1619,terminated,0 +620086,0,1862,terminated,0 +620087,0,1764,terminated,0 +620088,0,8750,timeout,0 +620089,0,8750,timeout,0 +620090,0,8750,timeout,0 +620091,0,8750,timeout,0 +620092,0,1865,terminated,0 +620093,0,8750,timeout,0 +620094,0,1752,terminated,0 +620095,0,8750,timeout,0 +620096,0,1861,terminated,0 +620097,0,8750,timeout,0 +620098,0,1771,terminated,0 +620099,0,189,terminated,0 diff --git a/policies/stack_blocks/deepseek1017-s1/policy.py b/policies/stack_blocks/deepseek1017-s1/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..2db5ff76b627809aa631ffa1a0e75ca78090aa21 --- /dev/null +++ b/policies/stack_blocks/deepseek1017-s1/policy.py @@ -0,0 +1,311 @@ +"""Vision-based scripted policy for the "stack blocks on the green pad" task. + +The controller is a deterministic state machine using only the robot's own +cameras and proprioception: + + 0 reach both arms toward the blocks on the table in front of the start pose + 1 wrist-camera visual servo onto the nearest block in each hand, then close + 2 lift the arms slowly into a carry pose + 3 walk around the table to the pad side + 4 step up to the table, lower the arms and align each held block over the + green pad (head-camera servo), releasing them one at a time + +Every phase has a bounded duration so the episode can never stall. +""" + +import numpy as np + +try: + import cv2 +except Exception: # pragma: no cover + cv2 = None + + +def _wrap(e): + return (e + np.pi) % (2.0 * np.pi) - np.pi + + +class Policy: + def __init__(self): + self.hold = None + + # ------------------------------------------------------------------ util + @staticmethod + def _mir(p): + return [p[0], -p[1], -p[2], p[3], -p[4], p[5], -p[6]] + + @staticmethod + def _blobs(im, which="red", minarea=8): + """Largest connected colour blobs: list of (area, cx, cy).""" + if im is None or cv2 is None: + return [] + a = np.asarray(im).astype(np.int16) + if a.ndim != 3 or a.shape[2] < 3: + return [] + r, g, b = a[:, :, 0], a[:, :, 1], a[:, :, 2] + if which == "red": + m = (r > 140) & (r > g + 60) & (r > b + 60) + else: + m = (g > 110) & (g > r + 40) & (g > b + 40) + n, lab, st, cen = cv2.connectedComponentsWithStats(m.astype(np.uint8), 8) + out = [] + for i in range(1, n): + if int(st[i, cv2.CC_STAT_AREA]) >= minarea: + out.append((int(st[i, cv2.CC_STAT_AREA]), + float(cen[i][0]), float(cen[i][1]))) + out.sort(reverse=True) + return out + + @staticmethod + def _pose(obs): + lo = np.asarray(obs["low_dim_obs"]) + return float(lo[21]), float(lo[22]), float(lo[24]) + + def _act(self, obs): + a = self.hold.copy() + a[2] = float(self.height) + a[4] = float(self.pitch) + a[5:12] = self.poseL + a[12:19] = self._mir(self.poseR) + a[19] = 1.0 if self.closedL else 0.0 + a[20] = 1.0 if self.closedR else 0.0 + return a + + # ----------------------------------------------------------------- reset + def reset(self, obs, tools): + self.hold = np.asarray(tools.hold_action(), dtype=np.float32) + self.phase = 0 + self.k = 0 + self.height = 0.65 + self.pitch = 0.30 + self.poseL = np.array([-0.40, 0.0, 0.0, 0.40, 0.0, 0.0, 0.0], np.float32) + self.poseR = np.array([-0.40, 0.0, 0.0, 0.40, 0.0, 0.0, 0.0], np.float32) + self.closedL = False + self.closedR = False + self.startL = self.poseL.copy() + self.startR = self.poseR.copy() + # carry pose verified to keep both blocks gripped while walking + self.carryL = np.array([-1.35, 0.05, 0.0, 1.15, 0.0, 0.0, 0.0], np.float32) + self.carryR = np.array([-1.35, -0.05, 0.0, 1.15, 0.0, 0.0, 0.0], np.float32) + # slightly tucked carry pose for the final approach to the table + self.tuckL = np.array([-1.15, 0.05, 0.0, 1.35, 0.0, 0.0, 0.0], np.float32) + self.tuckR = np.array([-1.15, -0.05, 0.0, 1.35, 0.0, 0.0, 0.0], np.float32) + # low pose over the table for releasing the blocks + self.lowL = np.array([-0.85, 0.12, 0.0, 0.85, 0.0, 0.0, 0.0], np.float32) + self.lowR = np.array([-0.85, -0.12, 0.0, 0.85, 0.0, 0.0, 0.0], np.float32) + self.waypoints = [(0.00, -2.30), (2.35, -2.30), (2.40, -0.25)] + self.wp = 0 + self.stall = 0 + self.xprev = None + + # ------------------------------------------------------------------- act + def act(self, obs, tools): + ph = self.phase + + # -- 0: begin the reach ----------------------------------------- + if ph == 0: + self.phase = 1 + self.k = 0 + return self._act(obs) + + # -- 1: wrist-camera servo onto a block in each hand ------------- + if ph == 1: + self.k += 1 + if self.k > 6 and self.k % 3 == 0: + bl = self._blobs(tools.image("left_wrist")) + br = self._blobs(tools.image("right_wrist")) + if bl and not self.closedL: + ar, cx, cy = bl[0] + self.poseL[1] = float(np.clip(self.poseL[1] + 0.004 * (43 - cx), -0.8, 0.8)) + self.poseL[0] = float(np.clip(self.poseL[0] - 0.003 * (58 - cy), -1.1, 0.2)) + if ar < 3200: + self.poseL[3] = min(self.poseL[3] + 0.03, 1.5) + else: + self.closedL = True + if br and not self.closedR: + ar, cx, cy = br[0] + self.poseR[1] = float(np.clip(self.poseR[1] - 0.004 * (43 - cx), -0.8, 0.8)) + self.poseR[0] = float(np.clip(self.poseR[0] - 0.003 * (58 - cy), -1.1, 0.2)) + if ar < 2100: + self.poseR[3] = min(self.poseR[3] + 0.03, 1.5) + else: + self.closedR = True + if (self.closedL and self.closedR) or self.k >= 145: + self.closedL = True + self.closedR = True + self.startL = self.poseL.copy() + self.startR = self.poseR.copy() + self.phase = 2 + self.k = 0 + return self._act(obs) + + # -- 2: close, lift slowly into the carry pose ------------------- + if ph == 2: + self.k += 1 + if self.k <= 12: + return self._act(obs) + u = min(1.0, (self.k - 12) / 55.0) + self.poseL = self.startL + (self.carryL - self.startL) * u + self.poseR = self.startR + (self.carryR - self.startR) * u + self.height = 0.65 + 0.09 * u + self.pitch = 0.30 * (1.0 - u) + if self.k > 72: + self.phase = 3 + self.k = 0 + self.wp = 0 + return self._act(obs) + + # -- 3: walk around the table to the pad side -------------------- + if ph == 3: + self.k += 1 + self.height = 0.74 + self.pitch = 0.0 + x, y, yaw = self._pose(obs) + a = self._act(obs) + if self.wp < len(self.waypoints) and self.k < 2600: + gx, gy = self.waypoints[self.wp] + dx, dy = gx - x, gy - y + d = float(np.hypot(dx, dy)) + if d < 0.20: + self.wp += 1 + return a + err = _wrap(float(np.arctan2(dy, dx)) - yaw) + if abs(err) > 0.5: + a[3] = float(np.clip(1.8 * err, -0.8, 0.8)) + a[0] = 0.0 + else: + a[3] = float(np.clip(1.5 * err, -0.4, 0.4)) + a[0] = float(np.clip(0.4 * min(1.0, d / 0.5), 0.08, 0.45)) + return a + err = _wrap(np.pi - yaw) + if abs(err) < 0.08: + self.phase = 4 + self.k = 0 + self.xprev = x + self.stall = 0 + return a + if abs(err) > 3.0: + err = 3.0 + a[3] = float(np.clip(2.0 * err, -0.9, 0.9)) + if abs(a[3]) < 0.06: + a[3] = float(0.06 * np.sign(err)) + a[0] = 0.0 + return a + + # -- 4: tuck the arms slightly and step in toward the table ------ + if ph == 4: + self.k += 1 + self.height = 0.74 + self.pitch = 0.0 + x, y, yaw = self._pose(obs) + ut = min(1.0, self.k / 22.0) + self.poseL = self.carryL + (self.tuckL - self.carryL) * ut + self.poseR = self.carryR + (self.tuckR - self.carryR) * ut + a = self._act(obs) + err = _wrap(np.pi - yaw) + a[3] = float(np.clip(1.5 * err, -0.3, 0.3)) + if self.xprev is not None and self.xprev - x < 0.004: + self.stall += 1 + else: + self.stall = 0 + self.xprev = x + if self.k <= 135 and x > 1.95 and self.stall < 25: + a[0] = 0.28 + return a + self.phase = 5 + self.k = 0 + self.tuckL = self.poseL.copy() + self.tuckR = self.poseR.copy() + return a + + # -- 5: lower the arms over the table ---------------------------- + if ph == 5: + self.k += 1 + self.height = 0.74 + u = min(1.0, self.k / 45.0) + self.pitch = 0.12 * u + self.poseL = self.tuckL + (self.lowL - self.tuckL) * u + self.poseR = self.tuckR + (self.lowR - self.tuckR) * u + if self.k > 52: + self.phase = 6 + self.k = 0 + return self._act(obs) + + # -- 6: align the right hand over the pad, release --------------- + if ph == 6: + self.k += 1 + self.height = 0.74 + self.pitch = 0.12 + a = self._act(obs) + if self.k > 4 and self.k % 2 == 0: + g = self._blobs(tools.image("head"), "green") + if g: + ex = 60.0 - g[0][1] + if abs(ex) > 2.5: + a[1] = float(np.clip(0.008 * ex, -0.22, 0.22)) + a[3] = 0.0 + if self.k > 75: + self.phase = 7 + self.k = 0 + return a + + # -- 7: open right, shift toward the left hand ------------------- + if ph == 7: + self.k += 1 + self.height = 0.74 + self.pitch = 0.12 + a = self._act(obs) + a[20] = 0.0 + self.poseR = self.carryR + if self.k > 10: + a[1] = -0.24 + if self.k > 55: + self.phase = 8 + self.k = 0 + return a + + # -- 8: align the left hand over the pad, release ---------------- + if ph == 8: + self.k += 1 + self.height = 0.74 + self.pitch = 0.12 + self.poseR = self.carryR + a = self._act(obs) + a[20] = 0.0 + if self.k > 4 and self.k % 2 == 0: + g = self._blobs(tools.image("head"), "green") + if g: + ex = 26.0 - g[0][1] + if abs(ex) > 2.5: + a[1] = float(np.clip(0.008 * ex, -0.22, 0.22)) + a[3] = 0.0 + if self.k > 85: + self.phase = 9 + self.k = 0 + return a + + # -- 9: release left, retract, settle ---------------------------- + if ph == 9: + self.k += 1 + self.height = 0.74 + u = min(1.0, self.k / 35.0) + self.pitch = 0.12 * (1.0 - u) + self.poseL = self.lowL + (self.carryL - self.lowL) * u + self.poseR = self.carryR + a = self._act(obs) + a[19] = 0.0 + a[20] = 0.0 + if self.k > 40: + self.phase = 10 + self.k = 0 + return a + + # -- 10: hold still --------------------------------------------- + self.height = 0.74 + self.pitch = 0.0 + self.poseL = self.carryL + self.poseR = self.carryR + a = self._act(obs) + a[19] = 0.0 + a[20] = 0.0 + return a