Add the final programs of 7 coding agents on all 20 tasks (420 sessions) (part 3)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- policies/put_cups/gpt61terra-s2/policy.pyAdded+62
- policies/put_cups/gpt61terra-s3/episodes.csvAdded+101
- policies/put_cups/gpt61terra-s3/policy.pyAdded+40
- policies/put_cups/gpt6sol-s1/episodes.csvAdded+101
- policies/put_cups/gpt6sol-s1/policy.pyAdded+97
- policies/put_cups/gpt6sol-s2/episodes.csvAdded+101
- policies/put_cups/gpt6sol-s2/policy.pyAdded+159
- policies/put_cups/gpt6sol-s3/episodes.csvAdded+101
- policies/put_cups/gpt6sol-s3/policy.pyAdded+154
- policies/put_cups/kimi31pro-s1/episodes.csvAdded+101
- policies/put_cups/kimi31pro-s1/policy.pyAdded+160
- policies/put_cups/kimi31pro-s2/episodes.csvAdded+101
- policies/put_cups/kimi31pro-s2/policy.pyAdded+221
- policies/put_cups/opus-s1/episodes.csvAdded+101
- policies/put_cups/opus-s1/policy.pyAdded+685
- policies/put_cups/opus-s2/cupvision.pyAdded+272
- policies/put_cups/opus-s2/episodes.csvAdded+101
- policies/put_cups/opus-s2/g1kin.pyAdded+168
- policies/put_cups/opus-s2/policy.pyAdded+592
- policies/put_cups/opus-s3/episodes.csvAdded+101
- policies/put_cups/opus-s3/g1kin.pyAdded+185
- policies/put_cups/opus-s3/policy.pyAdded+728
- policies/put_cups/opus-s3/vision.pyAdded+139
- policies/reach_target_dual/astra-s1/episodes.csvAdded+101
- policies/reach_target_dual/astra-s1/policy.pyAdded+168
- policies/reach_target_dual/astra-s2/episodes.csvAdded+101
- policies/reach_target_dual/astra-s2/policy.pyAdded+96
- policies/reach_target_dual/astra-s3/episodes.csvAdded+101
- policies/reach_target_dual/astra-s3/policy.pyAdded+118
- policies/reach_target_dual/deepseek1017-s1/episodes.csvAdded+101
- policies/reach_target_dual/deepseek1017-s1/policy.pyAdded+190
- policies/reach_target_dual/deepseek1017-s2/episodes.csvAdded+101
- policies/reach_target_dual/deepseek1017-s2/policy.pyAdded+268
- policies/reach_target_dual/deepseek1017-s3/episodes.csvAdded+101
- policies/reach_target_dual/deepseek1017-s3/policy.pyAdded+124
- policies/reach_target_dual/gpt61sol-s1/episodes.csvAdded+101
- policies/reach_target_dual/gpt61sol-s1/policy.pyAdded+170
- policies/reach_target_dual/gpt61sol-s2/episodes.csvAdded+101
- policies/reach_target_dual/gpt61sol-s2/policy.pyAdded+140
- policies/reach_target_dual/gpt61sol-s3/episodes.csvAdded+101
- policies/reach_target_dual/gpt61sol-s3/policy.pyAdded+113
- policies/reach_target_dual/gpt61terra-s1/episodes.csvAdded+101
- policies/reach_target_dual/gpt61terra-s1/policy.pyAdded+54
- policies/reach_target_dual/gpt61terra-s2/episodes.csvAdded+101
- policies/reach_target_dual/gpt61terra-s2/policy.pyAdded+57
- policies/reach_target_dual/gpt61terra-s3/episodes.csvAdded+101
- policies/reach_target_dual/gpt61terra-s3/policy.pyAdded+63
- policies/reach_target_dual/gpt6sol-s1/episodes.csvAdded+101
- policies/reach_target_dual/gpt6sol-s1/policy.pyAdded+125
- policies/reach_target_dual/gpt6sol-s2/episodes.csvAdded+101
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import 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 a123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,012345678910111213141516171819202122232425262728293031323334353637383940"""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 start123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697"""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 out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""Deterministic upper-body and base control for the cabinet task."""
import mathimport 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 action123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""Deterministic camera-guided cup handling policy."""
import cv2import 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160"""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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221"""Deterministic, hand-written controller for the cup-storage task.
The controller uses joint-space arm trajectories, a pelvis-position servo, andfinger 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 a123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685"""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 cv2import numpy as npfrom 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.8746480TOOLS = {'L': (0.155, 0.016, -0.046), 'R': (0.155, -0.016, -0.046)} # grasp centre in wrist frameLOOK_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
# ----------------------------------------------------------------------------- cupsZ_TOP = 0.806 # counter top heightCUP_R = 0.04RHV = 0.058 # radius of the visible handle loopRHG = 0.062 # radius of the grasp point on the handleZG = Z_TOP + 0.052U_REF = 43.0PSI_MAX = 0.7RT = 0.085 # grasp point distance from the cup axis (fingers are long)U_GRASP = 42.0CUP_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 constantsBASE = (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.16PLACE_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 = FalseFI = {'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 False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272"""Cup detection in the wrist cameras and stereo localisation (hand-written geometry)."""import numpy as npimport 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) heightR_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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168"""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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592"""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 controltick; `act` advances the phase generator by one tick and then computes the actionfrom the current arm targets. Arms are driven in Cartesian space with a dampedleast-squares IK on the G1 arm kinematics (g1kin.py); cups and door bars arelocated 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 themabove 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)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185"""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 npfrom 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, radCAM_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), wz123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728"""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 osimport sys
import numpy as np
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))import g1kin as K # noqa: E402import 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 = True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139"""Image processing for the policy (84x84 RGB from the robot cameras)."""import numpy as npfrom 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.933CUP_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()))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168"""Deterministic, hand-written binocular reaching with wrist visual feedback.
The head view initializes the reach. Each wrist independently centers itsassigned color and regulates apparent sphere size. All gains and thresholdsare fixed control constants; there are no trained models or seed-specific data."""
import cv2import 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.a123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596"""Deterministic, hand-written visual servo for simultaneous sphere touching.
Only RGB camera images and proprioception are used. Circle measurements arecomputed geometrically from the current image; no learned model or storedscene data is used. The head view initializes the approach, and the wristviews close the arm-control loops. Bright target colors indicate contact."""import numpy as npimport 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.a123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""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 npimport cv2from 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190"""Hand-written control policy for the reach_target_dual task.
Task: touch the red sphere with the left hand and the green sphere with theright 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. Thepolicy 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 motionF = 64.4CX = 36.7CY = 30.0
HEIGHT = 0.745
# reach posture measured at the initial pose of the robotL_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 raw123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268"""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 theright 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 npimport cv2
# ---------------------------------------------------------------------------# tuned constants# ---------------------------------------------------------------------------
# reach posture that points both wrist cameras at the spheresQ_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 steppingHEIGHT_REACH = 0.72 # pelvis height for the final reach (slight squat)WALK_VX = 0.30 # forward velocity command while approachingWALK_STEPS = 24 # control steps spent walking forward
SETTLE_STEPS = 30 # let the arms settle into the reach postureCOAST_STEPS = 10 # let the base stop before squattingSQUAT_STEPS = 16 # time given to the height command
# wrist-aim servoAIM_GAIN = 0.0010 # rad of wrist angle per pixel of centring errorAIM_DEADBAND = 3.0 # pxAIM_MAX_STEP = 0.05 # rad per control stepAIM_LIMIT = 1.40 # wrist pitch/yaw soft limit
# pattern searchPROBE_STEPS = 14 # control steps per probePROBE_DELTAS = (0.13, -0.13)PROBE_CAP = 46.0 # per-hand radius considered "touching"ACCEPT_MARGIN = 3.0SEARCH_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 sweepSWEEP_LO = 0.63 # lowest pelvis height of the sweepSWEEP_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 += 1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124"""Control policy for the dual-sphere reach task.
The robot must touch the red sphere with its left hand and the green spherewith its right hand at the same time. The only view of the scene is therobot-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 cv2import 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 raw123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170"""Hand-written, deterministic visual servoing for simultaneous two-hand reaching.
Uses only the three robot cameras and proprioception. Color segmentation tracksthe 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 cv2import 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""Colour perception and deterministic arm pattern search, with base feedback."""import cv2import 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113# Deterministic image feedback for simultaneous two-hand contact.# Runtime inputs are only robot cameras and proprioception.import numpy as npimport 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354import numpy as npimport cv2class 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 a123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import numpy as npimport 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 a123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import numpy as npimport 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 a123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125"""Deterministic image based reaching controller."""
import cv2import 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101seed,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,0policies/put_cups/gpt61terra-s2/policy.pyAdded+62
policies/put_cups/gpt61terra-s3/episodes.csvAdded+101
policies/put_cups/gpt61terra-s3/policy.pyAdded+40
policies/put_cups/gpt6sol-s1/episodes.csvAdded+101
policies/put_cups/gpt6sol-s1/policy.pyAdded+97
policies/put_cups/gpt6sol-s2/episodes.csvAdded+101
policies/put_cups/gpt6sol-s2/policy.pyAdded+159
policies/put_cups/gpt6sol-s3/episodes.csvAdded+101
policies/put_cups/gpt6sol-s3/policy.pyAdded+154
policies/put_cups/kimi31pro-s1/episodes.csvAdded+101
policies/put_cups/kimi31pro-s1/policy.pyAdded+160
policies/put_cups/kimi31pro-s2/episodes.csvAdded+101
policies/put_cups/kimi31pro-s2/policy.pyAdded+221
policies/put_cups/opus-s1/episodes.csvAdded+101
policies/put_cups/opus-s1/policy.pyAdded+685
policies/put_cups/opus-s2/cupvision.pyAdded+272
policies/put_cups/opus-s2/episodes.csvAdded+101
policies/put_cups/opus-s2/g1kin.pyAdded+168
policies/put_cups/opus-s2/policy.pyAdded+592
policies/put_cups/opus-s3/episodes.csvAdded+101
policies/put_cups/opus-s3/g1kin.pyAdded+185
policies/put_cups/opus-s3/policy.pyAdded+728
policies/put_cups/opus-s3/vision.pyAdded+139
policies/reach_target_dual/astra-s1/episodes.csvAdded+101
policies/reach_target_dual/astra-s1/policy.pyAdded+168
policies/reach_target_dual/astra-s2/episodes.csvAdded+101
policies/reach_target_dual/astra-s2/policy.pyAdded+96
policies/reach_target_dual/astra-s3/episodes.csvAdded+101
policies/reach_target_dual/astra-s3/policy.pyAdded+118
policies/reach_target_dual/deepseek1017-s1/episodes.csvAdded+101
policies/reach_target_dual/deepseek1017-s1/policy.pyAdded+190
policies/reach_target_dual/deepseek1017-s2/episodes.csvAdded+101
policies/reach_target_dual/deepseek1017-s2/policy.pyAdded+268
policies/reach_target_dual/deepseek1017-s3/episodes.csvAdded+101
policies/reach_target_dual/deepseek1017-s3/policy.pyAdded+124
policies/reach_target_dual/gpt61sol-s1/episodes.csvAdded+101
policies/reach_target_dual/gpt61sol-s1/policy.pyAdded+170
policies/reach_target_dual/gpt61sol-s2/episodes.csvAdded+101
policies/reach_target_dual/gpt61sol-s2/policy.pyAdded+140
policies/reach_target_dual/gpt61sol-s3/episodes.csvAdded+101
policies/reach_target_dual/gpt61sol-s3/policy.pyAdded+113
policies/reach_target_dual/gpt61terra-s1/episodes.csvAdded+101
policies/reach_target_dual/gpt61terra-s1/policy.pyAdded+54
policies/reach_target_dual/gpt61terra-s2/episodes.csvAdded+101
policies/reach_target_dual/gpt61terra-s2/policy.pyAdded+57
policies/reach_target_dual/gpt61terra-s3/episodes.csvAdded+101
policies/reach_target_dual/gpt61terra-s3/policy.pyAdded+63
policies/reach_target_dual/gpt6sol-s1/episodes.csvAdded+101
policies/reach_target_dual/gpt6sol-s1/policy.pyAdded+125
policies/reach_target_dual/gpt6sol-s2/episodes.csvAdded+101