phammminhhieu's picture
TRACE-VLA code snapshot 2026-11-22 11:47 +07: 456 canonical files + SHA256 manifest + sync report (part 2)
ae1ed83 verified
Raw History Blame Contribute Delete
5.9 kB
#!/usr/bin/env python3
"""TRACE-VLA v2 Data Factory — scripted OSC expert (data generation only).
Drives the Panda EEF with a proportional position controller over the
robosuite OSC 7D action space. Object poses come from the simulator
and are used ONLY to generate data; nothing privileged is written
into the model-input fields of the produced episodes (RGB, robot
state, executed actions).
Conventions verified by df_audit.py (21/11/2026):
- action[6] = +1 closes the gripper, -1 opens it;
- OSC axes are the world axes (+x action moves EEF +x);
- control_freq = 20; episodes are recorded at 10 Hz by applying each
recorded action for 2 env steps (action-repeat), mirroring the
10 fps LeRobot dataset.
Success for any goal is LIBERO's own predicate:
env.env._eval_predicate(('in', obj, 'basket_1_contain_region'))
cross-validated 20/20 against env.check_success() on the native goal.
"""
import numpy as np
from scipy.spatial.transform import Rotation
GRIP_OPEN = -1.0
GRIP_CLOSE = 1.0
def build_state(obs):
pos = np.asarray(obs["robot0_eef_pos"], dtype=np.float64)
quat = np.asarray(obs["robot0_eef_quat"], dtype=np.float64)
rotvec = Rotation.from_quat(quat).as_rotvec()
grip = np.asarray(obs["robot0_gripper_qpos"], dtype=np.float64)
return np.concatenate([pos, rotvec, grip]).astype(np.float32)
def goal_in(env, obj_name):
return bool(env.env._eval_predicate(
("in", obj_name, "basket_1_contain_region")))
class Recorder:
"""Accumulates one episode at 10 Hz (action-repeat 2)."""
def __init__(self, env):
self.env = env
self.agent, self.wrist, self.states, self.actions = [], [], [], []
def start(self, obs):
self._push(obs)
def _push(self, obs):
self.agent.append(np.asarray(obs["agentview_image"],
dtype=np.uint8))
self.wrist.append(np.asarray(obs["robot0_eye_in_hand_image"],
dtype=np.uint8))
self.states.append(build_state(obs))
def step(self, action):
a = np.asarray(action, dtype=np.float64)
obs = None
for _ in range(2):
obs, *_ = self.env.step(a)
self.actions.append(a.astype(np.float32))
self._push(obs)
return obs
def arrays(self):
# final zero action so frames/actions share length T
acts = self.actions + [np.zeros(7, dtype=np.float32)]
return {
"agentview": np.stack(self.agent),
"wrist": np.stack(self.wrist),
"states": np.stack(self.states),
"actions": np.stack(acts),
}
class ExpertFail(Exception):
pass
class ScriptedExpert:
def __init__(self, env, recorder):
self.env = env
self.rec = recorder
self.obs = None
def eef(self):
return np.asarray(self.obs["robot0_eef_pos"], dtype=np.float64)
def obj_pos(self, name):
return np.asarray(self.obs[f"{name}_pos"], dtype=np.float64)
def move_to(self, target, grip, tol=0.010, max_steps=90, gain=2.5):
target = np.asarray(target, dtype=np.float64)
for _ in range(max_steps):
d = target - self.eef()
if np.linalg.norm(d) < tol:
return
a = np.clip(gain * d, -0.9, 0.9)
self.obs = self.rec.step(
[a[0], a[1], a[2], 0.0, 0.0, 0.0, grip])
if np.linalg.norm(target - self.eef()) >= max(tol, 0.02):
raise ExpertFail(f"move_timeout target={target.round(3)} "
f"eef={self.eef().round(3)}")
def hold(self, grip, steps):
for _ in range(steps):
self.obs = self.rec.step([0, 0, 0, 0, 0, 0, grip])
def pick_place(self, target_name, basket_name="basket_1",
grasp_off=0.05):
"""Full pick-and-place of target into the basket.
Returns dict with grasp/place diagnostics. Raises ExpertFail
with a machine-readable reason on failure."""
obj0 = self.obj_pos(target_name).copy()
basket = self.obj_pos(basket_name).copy()
# 1. hover above the object
self.move_to(obj0 + [0, 0, 0.17], GRIP_OPEN, tol=0.012)
# 2. descend to grasp height (EEF z relative to object centre)
obj = self.obj_pos(target_name)
grasp_z = obj[2] + grasp_off
self.move_to([obj[0], obj[1], grasp_z], GRIP_OPEN, tol=0.006,
max_steps=120)
# 3. close gripper
self.hold(GRIP_CLOSE, 6)
# 4. lift and verify the grasp
self.move_to([obj[0], obj[1], grasp_z + 0.16], GRIP_CLOSE,
tol=0.012)
obj1 = self.obj_pos(target_name)
lifted = float(obj1[2] - obj0[2])
follow = float(np.linalg.norm(obj1[:2] - self.eef()[:2]))
if lifted < 0.04 or follow > 0.06:
raise ExpertFail(f"grasp_failed lift={lifted:.3f} "
f"follow={follow:.3f}")
held_off = float(obj1[2] - self.eef()[2]) # obj centre rel EEF
# 5. transit above the basket
self.move_to([basket[0], basket[1], 0.36], GRIP_CLOSE,
tol=0.015, max_steps=140)
# 6. descend so the held centre sits ~0.11 above basket origin
place_eef_z = basket[2] + 0.11 - held_off
self.move_to([basket[0], basket[1], place_eef_z], GRIP_CLOSE,
tol=0.010, max_steps=120)
# 7. release, retreat, settle
self.hold(GRIP_OPEN, 5)
self.move_to([basket[0], basket[1], 0.36], GRIP_OPEN,
tol=0.02, max_steps=100)
self.hold(GRIP_OPEN, 3)
ok = goal_in(self.env, target_name)
return {"success": ok, "lifted_m": lifted,
"held_off_m": held_off,
"obj_start": obj0.round(4).tolist(),
"obj_end": self.obj_pos(target_name).round(4).tolist()}