Download visualize.py from pndbotics/adam_lite_dataset: direct link, hf CLI and curl.
- Browser
- Download file 9.29 kB
-
https://huggingface.co/datasets/pndbotics/adam_lite_dataset/resolve/main/visualize.py
- Command line
-
hf download hf://datasets/pndbotics/adam_lite_dataset/visualize.py
-
curl -L -o visualize.py https://huggingface.co/datasets/pndbotics/adam_lite_dataset/resolve/main/visualize.py
9.29 kB
| import os, sys, math | |
| import json, time | |
| import numpy as np | |
| import argparse | |
| from isaacgym import gymtorch, gymapi | |
| import torch | |
| CURRENT_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| CSV_FRAME_RATE = 50.0 | |
| CSV_TOTAL_COLS = 36 | |
| CSV_ROOT_POS_SLICE = slice(0, 3) | |
| CSV_ROOT_QUAT_SLICE = slice(3, 7) | |
| CSV_DOF_SLICE = slice(7, 36) | |
| def get_label_indices(labels, prefix): | |
| return [i for i, label in enumerate(labels) if label.startswith(prefix)] | |
| def load_motion_data_json(json_path): | |
| with open(json_path, 'r') as f: | |
| motion = json.load(f) | |
| labels = motion.get('Labels', []) | |
| frames = np.array(motion['Frames'], dtype=np.float32) | |
| # 提取 DOF、root_pos、root_quat 的列索引 | |
| dof_indices = get_label_indices(labels, "dof_pos/") | |
| root_pos_indices = get_label_indices(labels, "root_pos/") | |
| root_quat_indices = get_label_indices(labels, "root_quat/") | |
| print(f"Found {len(dof_indices)} DOF channels:") | |
| for idx in dof_indices: | |
| print(f" {labels[idx]}") | |
| print(f"root_pos indices: {[labels[i] for i in root_pos_indices]}") | |
| print(f"root_quat indices: {[labels[i] for i in root_quat_indices]}") | |
| return ( | |
| frames[:, dof_indices], | |
| frames[:, root_pos_indices], | |
| frames[:, root_quat_indices], | |
| motion['FrameDuration'] | |
| ) | |
| def load_motion_data_csv(csv_path): | |
| frames = np.loadtxt(csv_path, delimiter=',', dtype=np.float32) | |
| if frames.ndim == 1: | |
| frames = frames[None, :] | |
| if frames.shape[1] < CSV_TOTAL_COLS: | |
| raise ValueError( | |
| f"CSV requires at least {CSV_TOTAL_COLS} columns, got {frames.shape[1]}: {csv_path}" | |
| ) | |
| if frames.shape[1] > CSV_TOTAL_COLS: | |
| print( | |
| f"CSV has {frames.shape[1]} columns, using first {CSV_TOTAL_COLS} columns: {csv_path}" | |
| ) | |
| frames = frames[:, :CSV_TOTAL_COLS] | |
| print(f"Loaded CSV motion: {csv_path}") | |
| print(f"root_pos columns: {CSV_ROOT_POS_SLICE.start + 1}~{CSV_ROOT_POS_SLICE.stop}") | |
| print(f"root_quat columns: {CSV_ROOT_QUAT_SLICE.start + 1}~{CSV_ROOT_QUAT_SLICE.stop}") | |
| print(f"dof columns: {CSV_DOF_SLICE.start + 1}~{CSV_DOF_SLICE.stop}") | |
| return ( | |
| frames[:, CSV_DOF_SLICE], | |
| frames[:, CSV_ROOT_POS_SLICE], | |
| frames[:, CSV_ROOT_QUAT_SLICE], | |
| 1.0 / CSV_FRAME_RATE | |
| ) | |
| def load_motion_data(motion_path): | |
| ext = os.path.splitext(motion_path)[1].lower() | |
| if ext == ".json": | |
| return load_motion_data_json(motion_path) | |
| if ext == ".csv": | |
| return load_motion_data_csv(motion_path) | |
| raise ValueError(f"Unsupported motion file format: {motion_path}") | |
| def set_base_pose(gym, sim, env, actor, root_pos, root_quat): | |
| """ | |
| 设置机器人 base link 的位置和旋转 | |
| :param root_pos: [x, y, z] | |
| :param root_quat: [x, y, z, w] | |
| """ | |
| root_state_tensor = gym.acquire_actor_root_state_tensor(sim) | |
| root_state = gymtorch.wrap_tensor(root_state_tensor) | |
| # 获取 actor 在 tensor 中的索引(通常为 0,如果你只加载了一个 actor) | |
| actor_index = 0 | |
| # 更新 base 位置和四元数 | |
| root_state[actor_index, :3] = torch.tensor(root_pos, dtype=torch.float32) | |
| root_state[actor_index, 3:7] = torch.tensor(root_quat, dtype=torch.float32) | |
| # 写回物理引擎 | |
| gym.set_actor_root_state_tensor(sim, root_state_tensor) | |
| def set_dof_positions(gym, env, actor, target_pos): | |
| dof_states = np.zeros(len(target_pos), dtype=gymapi.DofState.dtype) | |
| dof_states['pos'] = target_pos | |
| dof_states['vel'] = np.zeros_like(target_pos) | |
| gym.set_actor_dof_states(env, actor, dof_states, gymapi.STATE_POS + gymapi.STATE_VEL) | |
| def parse_args(): | |
| parser = argparse.ArgumentParser(description="Isaac Gym Preview 4 Motion Visualizer") | |
| parser.add_argument('--file_name', type=str, | |
| default="mixamo/low_jump.json", | |
| help='Motion file name (.json or .csv). Default: "mixamo/low_jump.json"') | |
| parser.add_argument('--robot_type', type=str, | |
| choices=['adam_lite', 'adam_sp'], | |
| default='adam_lite', | |
| help='Robot type to load. Default: "adam_lite"') | |
| return parser.parse_args() | |
| def resolve_existing_path(candidates): | |
| for rel_path in candidates: | |
| abs_path = os.path.join(CURRENT_DIR, rel_path) | |
| if os.path.exists(abs_path): | |
| return rel_path | |
| raise FileNotFoundError(f"No valid path found in candidates: {candidates}") | |
| def get_robot_paths(robot_type): | |
| if robot_type == "adam_lite": | |
| urdf_path = resolve_existing_path([ | |
| "robot_description/adam_lite/urdf/adam_lite.urdf", | |
| "robot_description/adam_lite/adam_lite.urdf", | |
| ]) | |
| motion_dir = "adam_lite" | |
| elif robot_type == "adam_sp": | |
| urdf_path = resolve_existing_path([ | |
| "robot_description/adam_sp/urdf/adam_sp.urdf", | |
| "robot_description/adam_sp/adam_sp.urdf", | |
| ]) | |
| motion_dir = "adam_sp" | |
| else: | |
| raise ValueError(f"Unknown robot_type: {robot_type}") | |
| return urdf_path, motion_dir | |
| def main(): | |
| args = parse_args() | |
| # 加载机器人资产 | |
| asset_path, motion_dir = get_robot_paths(args.robot_type) | |
| asset_root = os.path.dirname(asset_path) | |
| asset_file = os.path.basename(asset_path) | |
| # 加载动作数据 | |
| motion_path = os.path.join(CURRENT_DIR, motion_dir, args.file_name) | |
| frames_dof, frames_root_pos, frames_root_quat, frame_duration = load_motion_data(motion_path) | |
| num_frames = len(frames_dof) | |
| current_frame = 0 | |
| # 初始化 gym | |
| gym = gymapi.acquire_gym() | |
| # 设置仿真参数 | |
| sim_params = gymapi.SimParams() | |
| sim_params.dt = frame_duration # 模拟频率 | |
| sim_params.substeps = 2 | |
| sim_params.up_axis = gymapi.UP_AXIS_Z | |
| sim_params.gravity = gymapi.Vec3(0.0, 0.0, 0.0) # 关闭重力 | |
| sim_params.use_gpu_pipeline = False # 禁用 GPU pipeline(更简单) | |
| sim = gym.create_sim(0, 0, gymapi.SIM_PHYSX, sim_params) | |
| if sim is None: | |
| raise Exception("Failed to create sim") | |
| # 加载地面 | |
| plane_params = gymapi.PlaneParams() | |
| plane_params.normal = gymapi.Vec3(0, 0, 1) | |
| gym.add_ground(sim, plane_params) | |
| asset_options = gymapi.AssetOptions() | |
| asset_options.fix_base_link = False | |
| asset_options.disable_gravity = True | |
| asset_options.collapse_fixed_joints = True | |
| robot_asset = gym.load_asset(sim, asset_root, asset_file, asset_options) | |
| # 获取 DOF 数量 | |
| num_dof = gym.get_asset_dof_count(robot_asset) | |
| if frames_dof.shape[1] != num_dof: | |
| print( | |
| f"DOF count mismatch: motion has {frames_dof.shape[1]}, " | |
| f"asset requires {num_dof}. Auto-aligning." | |
| ) | |
| if frames_dof.shape[1] > num_dof: | |
| frames_dof = frames_dof[:, :num_dof] | |
| else: | |
| pad = np.zeros((frames_dof.shape[0], num_dof - frames_dof.shape[1]), dtype=np.float32) | |
| frames_dof = np.concatenate([frames_dof, pad], axis=1) | |
| # 创建环境 | |
| spacing = 1.0 | |
| lower = gymapi.Vec3(-spacing, -spacing, 0.0) | |
| upper = gymapi.Vec3(spacing, spacing, spacing) | |
| env = gym.create_env(sim, lower, upper, 8) | |
| # 创建机器人 actor | |
| pose = gymapi.Transform() | |
| pose.p = gymapi.Vec3(0.0, 0.0, 1.0) | |
| pose.r = gymapi.Quat(0.0, 0.0, 0.0, 1.0) | |
| actor = gym.create_actor(env, robot_asset, pose, "actor", 0, 0) | |
| cam_props = gymapi.CameraProperties() | |
| viewer = gym.create_viewer(sim, cam_props) | |
| if viewer is None: | |
| raise Exception("Failed to create viewer") | |
| # 设置相机参数 | |
| CAMERA_DISTANCE = -3.0 # 距离 base 的距离 | |
| CAMERA_HEIGHT = 1.0 # 高度 | |
| CAMERA_ANGLE = math.radians(90) # 视角角度(弧度) | |
| while not gym.query_viewer_has_closed(viewer): | |
| if current_frame < num_frames: | |
| target_dof = frames_dof[current_frame] | |
| target_root_pos = frames_root_pos[current_frame] | |
| target_root_quat = frames_root_quat[current_frame] | |
| # 设置 Base 位姿 | |
| set_base_pose(gym, sim, env, actor, target_root_pos, target_root_quat) | |
| # 设置关节角度 | |
| set_dof_positions(gym, env, actor, target_dof) | |
| current_frame += 1 | |
| else: | |
| print("Animation finished.") | |
| break | |
| # Step simulation and render | |
| gym.simulate(sim) | |
| gym.fetch_results(sim, True) | |
| gym.step_graphics(sim) | |
| # 获取机器人 base 位置 | |
| root_state_tensor = gym.acquire_actor_root_state_tensor(sim) | |
| root_state = gymtorch.wrap_tensor(root_state_tensor) | |
| root_pos = root_state[0, :3].cpu().numpy() | |
| # 使用球面坐标系计算相机位置 | |
| cam_x = root_pos[0] + CAMERA_DISTANCE * math.cos(CAMERA_ANGLE) | |
| cam_y = root_pos[1] + CAMERA_DISTANCE * math.sin(CAMERA_ANGLE) | |
| cam_z = root_pos[2] + CAMERA_HEIGHT | |
| cam_pos = gymapi.Vec3(cam_x, cam_y, cam_z) | |
| cam_target = gymapi.Vec3(root_pos[0], root_pos[1], root_pos[2]) | |
| # 更新相机视角 | |
| gym.viewer_camera_look_at(viewer, None, cam_pos, cam_target) | |
| gym.draw_viewer(viewer, sim, True) | |
| gym.sync_frame_time(sim) | |
| time.sleep(0.001) | |
| if __name__ == "__main__": | |
| main() | |