Linslab's picture
Move frozen Astra policies to astra/<task>/ (DualArmHammerHandover-v1 .. DualArmPushBox-v1)
67e0b67 verified
Raw History Blame Contribute Delete
4.66 kB
"""Unrehearsed D20 draft: observation-conditioned nonparametric action retrieval.
No environment, kinematics, hidden state, neural model, or online weight updates.
"""
from pathlib import Path
import numpy as np
import cv2
KEYS = ('panda_leaphand-1', 'panda_leaphand_left-0')
CAMERAS = ('front_camera', 'top_camera')
_BANK = None
_phase = None
_last_step = 0
_last_action = None
def visual_features(rgb):
result = []
for camera in CAMERAS:
im = np.asarray(rgb[camera])
if im.ndim == 4 and im.shape[0] == 1:
im = im[0]
if im.ndim != 3 or im.shape[2] != 3 or im.dtype != np.uint8:
raise ValueError('RGB must be uint8 HWC or 1HWC')
# Fixed fractional crop includes the tabletop, dish, hands and clay.
h, w = im.shape[:2]
im = im[int(.25*h):int(.94*h), int(.12*w):int(.91*w)]
small = cv2.resize(im, (24, 24), interpolation=cv2.INTER_AREA)
hsv = cv2.cvtColor(im, cv2.COLOR_RGB2HSV)
# Color-independent clay occupancy; avoids treating a color as an arm ID.
mask = ((hsv[..., 1] > 120) & (hsv[..., 2] > 45)).astype(np.float32)
mask = cv2.resize(mask, (24, 24), interpolation=cv2.INTER_AREA)
result.append(np.r_[small.reshape(-1).astype(np.float32)/255., mask.reshape(-1)])
return np.stack(result)
def proprio_features(proprio):
values = []
for kind in ('qpos', 'qvel'):
parts = []
for key in KEYS:
v = np.asarray(proprio['agent/'+key+'/'+kind], dtype=np.float32).reshape(-1)
if v.size != 23 or not np.isfinite(v).all():
raise ValueError('Expected 23 finite joint values per robot')
parts.append(v)
values.append(np.concatenate(parts))
return values
def _bank():
global _BANK
if _BANK is None:
with np.load(Path(__file__).with_name('reference_bank.npz'), allow_pickle=False) as f:
_BANK = {k: f[k] for k in f.files}
return _BANK
def reset_episode():
global _phase, _last_step, _last_action
_phase, _last_step, _last_action = None, 0, None
def act(obs):
global _phase, _last_step, _last_action
step = int(obs['step_id'])
# Runner already owns the charged hold. At most 599 subsequent native actions.
if step >= 600:
return None
if step < 1:
raise ValueError('step_id starts at 1 after the runner hold')
if step < _last_step:
reset_episode()
if step == _last_step and _last_action is not None:
return _last_action.copy()
try:
q, v = proprio_features(obs['proprioception'])
visual = visual_features(obs['rgb'])
except (KeyError, ValueError, TypeError):
# Missing/invalid observations cannot establish safe task progression.
return None
b = _bank()
p = b['phase']
if _phase is None:
valid = p <= .12
else:
# Observation-selected progression, with bounded local recovery.
clock = (step-1)/575.
lower = max(0., _phase-.02, clock-.018)
upper = min(1., max(_phase+.04, clock+.025))
valid = (p >= lower) & (p <= upper)
ix = np.flatnonzero(valid)
scale = np.tile(np.r_[np.full(7,.18),np.full(16,.35)],2)
dq = (b['qpos'][ix]-q)/scale
joint_d = .7*np.mean(dq[:,np.r_[0:7,23:30]]**2,axis=1) + .3*np.mean(dq[:,np.r_[7:23,30:46]]**2,axis=1)
velocity_d = np.mean(((b['qvel'][ix]-v)/1.2)**2,axis=1)
# Proprioception narrows candidates; RGB then chooses scene-compatible states.
ix = ix[np.argsort(joint_d + .04*velocity_d)[:min(160,len(ix))]]
dq = (b['qpos'][ix]-q)/scale
joint_d = .7*np.mean(dq[:,np.r_[0:7,23:30]]**2,axis=1) + .3*np.mean(dq[:,np.r_[7:23,30:46]]**2,axis=1)
dv = b['visual'][ix].astype(np.float32)-visual
image_d = np.mean(dv[:,:,:1728]**2,axis=(1,2))/.08**2
clay_d = np.mean(dv[:,:,1728:]**2,axis=(1,2))/.10**2
cost = joint_d + .35*image_d + .35*clay_d + .04*np.mean(((b['qvel'][ix]-v)/1.2)**2,axis=1)
if _phase is not None:
cost += .05*((p[ix]-_phase)/.04)**2
best = int(np.argmin(cost))
# Never blend different phases (e.g., descend and retract).
compatible = np.flatnonzero(np.abs(p[ix]-p[ix[best]])<.012)
chosen = compatible[np.argsort(cost[compatible])[:5]]
weight = np.exp(-(cost[chosen]-cost[chosen].min())/.10)
weight /= weight.sum()
action = weight @ b['actions'][ix[chosen]]
_phase = float(weight @ p[ix[chosen]])
action = np.clip(action, -1., 1.).astype(np.float32)
if action.shape != (44,) or not np.isfinite(action).all():
return None
_last_step, _last_action = step, action.copy()
return action