starry0929's picture
Add missing 1500-case scene, robot models, physical revision and IK dependencies
35f4d03 verified
Raw History Blame Contribute Delete
5.85 kB
"""
读取 MimicGen 源本体(UR5e)演示,并提取 Track A 需要的 GT。
实现要点:把演示里的完整 MuJoCo 状态在源本体环境里**一次性重放**,同时拿到
· 源末端控制点(grip_site)的位姿轨迹 —— 这是要被 retarget 的东西
· 物体位姿轨迹、抓取事件时序、任务成功判定 —— 这是与本体形态无关的 GT
注意不要用 hdf5 里的 `robot0_eef_quat` 观测:它是 right_hand **body** 的姿态,
而 OSC 控制器控制的是 grip_**site**,两者相差一个 90° 固定旋转。混用会引入
一个恒定姿态偏置(这本身就是"帧约定不一致"类 retarget 失败的典型形态)。
"""
import json
from dataclasses import dataclass
from typing import Dict, Optional
import h5py
import numpy as np
from . import envs as E
@dataclass
class SourceDemo:
"""源本体演示里、retarget 所需要的全部输入。"""
demo_key: str
env_name: str
source_robot: str
eef_pos: np.ndarray # (T, 3) grip_site 位置(世界系)
eef_mat: np.ndarray # (T, 3, 3) grip_site 姿态(世界系)
gripper_cmd: np.ndarray # (T,) +1 闭合 / -1 张开
raw_actions: np.ndarray # (T, 7) 源演示原始动作(open_loop baseline 用)
object_init: Dict[str, np.ndarray]
n_steps: int
scene_xml: str = None
@dataclass
class GTTrace:
"""源演示自身产生的 GT(形态无关的任务不变量)。"""
object_traj: Dict[str, np.ndarray] # {joint_name: (T, 7)}
primary_joint: str # 位移最大的物体自由关节(任务相关物体)
grasp_flags: np.ndarray # (T,) 是否处于稳定抓取
grasp_step: int
release_step: int
success: Optional[bool] # None: source success was not measured
def collision_geoms_of(env, prefix):
"""按名字前缀取物体的碰撞几何体(排除 _visual)。"""
return [
env.sim.model.geom_id2name(i)
for i in range(env.sim.model.ngeom)
if (env.sim.model.geom_id2name(i) or "").startswith(prefix)
and not (env.sim.model.geom_id2name(i) or "").endswith("_visual")
]
def _pick_primary_joint(traj, grasp):
"""
判定"被操作的物体"。
不能简单用位移最大:robosuite 在 single_object_mode 下会把任务无关的物体
(如 Square_D0 里的 RoundNut)停放在 (10,10,10) 之外,它掉落产生的位移
高达 10m,会盖过真正被操作物体的 0.35m。
因此优先用"在源演示中被夹爪稳定抓取过"来判定,抓取时长最久者胜;
若都没抓取记录,则退化为在工作空间内(|xy| < 3m)位移最大者。
"""
grasped = {j: int(g.sum()) for j, g in grasp.items() if g.any()}
if grasped:
return max(grasped, key=grasped.get)
in_ws = {
j: float(np.linalg.norm(v[-1, :3] - v[0, :3]))
for j, v in traj.items()
if np.abs(v[0, :2]).max() < 3.0
}
pool = in_ws or {j: float(np.linalg.norm(v[-1, :3] - v[0, :3])) for j, v in traj.items()}
return max(pool, key=pool.get)
def load_demo(dataset_path, demo_key, source_env):
"""一次重放,同时返回 SourceDemo 与 GTTrace。"""
with h5py.File(dataset_path, "r") as f:
d = f["data"][demo_key]
raw_actions = np.array(d["actions"])
states = np.array(d["states"])
model_xml = d.attrs["model_file"]
env_args = json.loads(f["data"].attrs["env_args"])
source_env.reset()
scene_xml = source_env.edit_model_xml(model_xml)
source_env.reset_from_xml_string(scene_xml)
source_env.sim.reset()
obj_joints = E.discover_object_joints(source_env)
obj_geoms = {
j: collision_geoms_of(source_env, j.split("_joint")[0]) for j in obj_joints
}
T_len = len(states)
eef_pos = np.zeros((T_len, 3))
eef_mat = np.zeros((T_len, 3, 3))
traj = {j: np.zeros((T_len, 7)) for j in obj_joints}
grasp = {j: np.zeros(T_len, dtype=bool) for j in obj_joints}
for t in range(T_len):
source_env.sim.set_state_from_flattened(states[t])
source_env.sim.forward()
source_env._get_observations(force_update=True)
p, m = E.eef_pose(source_env)
eef_pos[t], eef_mat[t] = p, m
for j in obj_joints:
traj[j][t] = source_env.sim.data.get_joint_qpos(j)
grasp[j][t] = bool(
source_env._check_grasp(
gripper=source_env.robots[0].gripper, object_geoms=obj_geoms[j]
)
)
# Public demonstrations are accepted without a source-task success check.
from scene_binding import nonrobot_joint_state
source_env.sim.set_state_from_flattened(states[0]);source_env.sim.forward()
object_init = nonrobot_joint_state(source_env)
primary_joint = _pick_primary_joint(traj, grasp)
gflags = grasp[primary_joint]
gidx = np.where(gflags)[0]
grasp_step = int(gidx[0]) if len(gidx) else -1
release_step = -1
if grasp_step >= 0:
after = np.where(~gflags[grasp_step:])[0]
release_step = int(grasp_step + after[0]) if len(after) else -1
source_env.sim.set_state_from_flattened(states[-1])
source_env.sim.forward()
demo = SourceDemo(
demo_key=demo_key,
env_name=env_args["env_name"],
source_robot=env_args["env_kwargs"]["robots"][0],
eef_pos=eef_pos,
eef_mat=eef_mat,
gripper_cmd=raw_actions[:, -1],
raw_actions=raw_actions,
object_init=object_init,
scene_xml=scene_xml,
n_steps=T_len,
)
gt = GTTrace(
object_traj=traj,
primary_joint=primary_joint,
grasp_flags=gflags,
grasp_step=grasp_step,
release_step=release_step,
success=None,
)
return demo, gt