"""Unrehearsed D20 observation-neighbor draft; no neural models or environment imports.""" from pathlib import Path import numpy as np import cv2 CAMERAS = ('front_camera', 'top_camera') PATHS = tuple(f'agent/panda-{r}/{k}' for r in range(2) for k in ('qpos','qvel')) _bank = None _progress = None _terminal_count = 0 def reset_episode(): global _progress, _terminal_count _progress = None _terminal_count = 0 def image_feature(rgb): features = [] 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('Expected uint8 RGB HWC or 1HWC') h, w = im.shape[:2] if min(h,w) < 8: raise ValueError('Image too small') # Central workspace crop; fixed fractional crop, not an assumed object pose. im = im[int(.18*h):int(.90*h), int(.12*w):int(.88*w)] features.append(cv2.resize(im, (16,16), interpolation=cv2.INTER_AREA).reshape(-1)/255.) return np.concatenate(features).astype(np.float32) def proprio_feature(proprio): values = [np.asarray(proprio[p],dtype=np.float32).reshape(-1) for p in PATHS] if any(v.size != 9 or not np.isfinite(v).all() for v in values): raise ValueError('Expected four finite nine-element proprio arrays') q = np.concatenate([values[0], values[2]]) v = np.concatenate([values[1], values[3]]) return q, v def _hold(q): a = np.zeros(14, dtype=np.float32) a[[6,13]] = 2*(q[[7,16]]+.01)/.05-1 if np.any(np.abs(a)>1): return None return a def act(obs): global _bank, _progress, _terminal_count # step 1 is already after runner's charged initial hold. Never emit that hold here. step = int(obs.get('step_id', 1)) if step >= 400 or step < 1: return None try: q,v = proprio_feature(obs['proprioception']) im = image_feature(obs['rgb']) except (KeyError, ValueError, TypeError): return None 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} b = _bank # All twenty demos remain eligible; do not identify a scene/seed or replay a trajectory. dq = (b['q']-q)/np.tile([.25]*7+[.02,.02],2) qdist = np.mean(dq*dq,axis=1) vdist = np.mean(np.minimum((b['v']-v)**2,4),axis=1) candidates = np.arange(len(qdist)) if _progress is not None: candidates = candidates[(b['phase'] >= _progress-.04)&(b['phase'] <= _progress+.08)] if candidates.size == 0: return _hold(q) # Coarse proprio retrieval followed by current-image reranking. coarse = qdist[candidates]+.03*vdist[candidates] candidates = candidates[np.argsort(coarse)[:96]] visual = np.mean((b['image'][candidates]-im)**2,axis=1) score = qdist[candidates]+.03*vdist[candidates]+35*visual if _progress is not None: score += .2*(b['phase'][candidates]-_progress)**2 order = np.argsort(score) best = candidates[order[0]] # Hand-selected, uncalibrated OOD limits; abstain from motion on gross mismatch. if qdist[best] > 4 or visual[order[0]] > .10: _terminal_count = 0 return _hold(q) _progress = float(b['phase'][best]) terminal = bool(b['terminal'][best]) and qdist[best] < .15 and visual[order[0]] < .015 _terminal_count = _terminal_count+1 if terminal else 0 if _terminal_count >= 5: return None # Resemblance to demonstrated endpoint, not a success certificate. # Blend only nearby labels of compatible progress, reducing sign cancellation at transitions. near = candidates[order[:5]] near = near[np.abs(b['phase'][near]-_progress)<.012] weights = np.exp(-(qdist[near]+.03*vdist[near]+35*np.mean((b['image'][near]-im)**2,axis=1))/ .08) weights = np.maximum(weights,1e-12);weights /= weights.sum() action = np.sum(b['action'][near]*weights[:,None],axis=0) return np.clip(action,-1,1).astype(np.float32)