diff --git a/.TimeRecord b/.TimeRecord new file mode 100644 index 0000000000000000000000000000000000000000..7a258c156f1ae21b0c134105d9e08e473e34ec35 --- /dev/null +++ b/.TimeRecord @@ -0,0 +1 @@ +u Mr4Z4yC 36QwinZcFfRldpR == \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..d76e0472042f68317ac62e43adf19284eee241bf --- /dev/null +++ b/LICENSE @@ -0,0 +1,8 @@ +Copyright 2026 ATEC (Advanced Technology Exploration Community) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/atec_robot_model/.gitattributes b/atec_robot_model/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..e7611ba3a3bc9880805c78f77616064787e781cf --- /dev/null +++ b/atec_robot_model/.gitattributes @@ -0,0 +1,6 @@ +*.png filter=lfs diff=lfs merge=lfs -text +*.usd filter=lfs diff=lfs merge=lfs -text +*.usda filter=lfs diff=lfs merge=lfs -text +*.yaml filter=lfs diff=lfs merge=lfs -text +*.hdr filter=lfs diff=lfs merge=lfs -text +*.pt filter=lfs diff=lfs merge=lfs -text \ No newline at end of file diff --git a/atec_robot_model/README.md b/atec_robot_model/README.md new file mode 100644 index 0000000000000000000000000000000000000000..dce5adb99218579da0151441d566fd34f1d83122 --- /dev/null +++ b/atec_robot_model/README.md @@ -0,0 +1,27 @@ +# atec_robot_model + +This repository provides robot and object 3D models for simulation and different environments. + +## Repository Overview + +- `robot/`: robot model assets (USD/USDA and configuration) +- `objects/`: task-related object assets +- `scene/`: task-related scene assets +- `baseline/`: baseline policy weight + +## Git Clone (with Git LFS) + +This repository stores model files with **Git LFS** + +Clone repository + +```bash +git clone https://github.com/skywoodsz/atec_robot_model.git +cd atec_robot_model +``` + +Pull LFS files + +```bash +git lfs pull +``` diff --git a/atec_robot_model/robot/piper/configuration/piper_physics.usd b/atec_robot_model/robot/piper/configuration/piper_physics.usd new file mode 100644 index 0000000000000000000000000000000000000000..2aa16bd1f5c8ffa5909f13fe9a4abb29265e7b53 Binary files /dev/null and b/atec_robot_model/robot/piper/configuration/piper_physics.usd differ diff --git a/atec_robot_model/robot/piper/configuration/piper_sensor.usd b/atec_robot_model/robot/piper/configuration/piper_sensor.usd new file mode 100644 index 0000000000000000000000000000000000000000..7cbc71c0e946cc41a4546940b6298daaf1ab4197 Binary files /dev/null and b/atec_robot_model/robot/piper/configuration/piper_sensor.usd differ diff --git a/atec_robot_model/robot/tron1/configuration/WF_TRON1A_physics.usd b/atec_robot_model/robot/tron1/configuration/WF_TRON1A_physics.usd new file mode 100644 index 0000000000000000000000000000000000000000..0662e09b71135f87120a4119cd68e5f275039e60 Binary files /dev/null and b/atec_robot_model/robot/tron1/configuration/WF_TRON1A_physics.usd differ diff --git a/atec_robot_model/robot/tron1/configuration/WF_TRON1A_sensor.usd b/atec_robot_model/robot/tron1/configuration/WF_TRON1A_sensor.usd new file mode 100644 index 0000000000000000000000000000000000000000..9d5f42262d1e6d77d64e6db44e53d87d67a7f856 Binary files /dev/null and b/atec_robot_model/robot/tron1/configuration/WF_TRON1A_sensor.usd differ diff --git a/atec_robot_model/robot/tron2/SFYG_TRON2A/configuration/robot_physics.usd b/atec_robot_model/robot/tron2/SFYG_TRON2A/configuration/robot_physics.usd new file mode 100644 index 0000000000000000000000000000000000000000..eee32b216fd76320cd6435e7ca1c8b0de3f5a6e4 Binary files /dev/null and b/atec_robot_model/robot/tron2/SFYG_TRON2A/configuration/robot_physics.usd differ diff --git a/atec_robot_model/robot/tron2/SFYG_TRON2A/configuration/robot_robot.usd b/atec_robot_model/robot/tron2/SFYG_TRON2A/configuration/robot_robot.usd new file mode 100644 index 0000000000000000000000000000000000000000..7362d03619b07b5197d0fa9f9e2c5a8bab4fc879 Binary files /dev/null and b/atec_robot_model/robot/tron2/SFYG_TRON2A/configuration/robot_robot.usd differ diff --git a/atec_robot_model/robot/tron2/SFYG_TRON2A/configuration/robot_sensor.usd b/atec_robot_model/robot/tron2/SFYG_TRON2A/configuration/robot_sensor.usd new file mode 100644 index 0000000000000000000000000000000000000000..5481674dfda5c101a952dca58b3e3d3709b612cc Binary files /dev/null and b/atec_robot_model/robot/tron2/SFYG_TRON2A/configuration/robot_sensor.usd differ diff --git a/atec_robot_model/robot/tron2/SFYG_TRON2A/robot.usd b/atec_robot_model/robot/tron2/SFYG_TRON2A/robot.usd new file mode 100644 index 0000000000000000000000000000000000000000..5b4d8093872c8778f0eae523001bf2b682d3aa3b Binary files /dev/null and b/atec_robot_model/robot/tron2/SFYG_TRON2A/robot.usd differ diff --git a/atec_robot_model/robot/tron2/WFYG_TRON2A/configuration/robot_physics.usd b/atec_robot_model/robot/tron2/WFYG_TRON2A/configuration/robot_physics.usd new file mode 100644 index 0000000000000000000000000000000000000000..1055dc9af9cc5aad6da784b0d58c268365e23760 Binary files /dev/null and b/atec_robot_model/robot/tron2/WFYG_TRON2A/configuration/robot_physics.usd differ diff --git a/atec_robot_model/robot/tron2/WFYG_TRON2A/configuration/robot_robot.usd b/atec_robot_model/robot/tron2/WFYG_TRON2A/configuration/robot_robot.usd new file mode 100644 index 0000000000000000000000000000000000000000..29911a0c6bac5fc12ae6860cbbda0568b068c411 Binary files /dev/null and b/atec_robot_model/robot/tron2/WFYG_TRON2A/configuration/robot_robot.usd differ diff --git a/atec_robot_model/robot/tron2/WFYG_TRON2A/configuration/robot_sensor.usd b/atec_robot_model/robot/tron2/WFYG_TRON2A/configuration/robot_sensor.usd new file mode 100644 index 0000000000000000000000000000000000000000..5481674dfda5c101a952dca58b3e3d3709b612cc Binary files /dev/null and b/atec_robot_model/robot/tron2/WFYG_TRON2A/configuration/robot_sensor.usd differ diff --git a/atec_robot_model/robot/tron2/WFYG_TRON2A/robot.usd b/atec_robot_model/robot/tron2/WFYG_TRON2A/robot.usd new file mode 100644 index 0000000000000000000000000000000000000000..5b4d8093872c8778f0eae523001bf2b682d3aa3b Binary files /dev/null and b/atec_robot_model/robot/tron2/WFYG_TRON2A/robot.usd differ diff --git a/atec_robot_model/scene/plane/default_environment.usd b/atec_robot_model/scene/plane/default_environment.usd new file mode 100644 index 0000000000000000000000000000000000000000..08c5e28b60f7d8e901ac2091351238c496e2df9d Binary files /dev/null and b/atec_robot_model/scene/plane/default_environment.usd differ diff --git a/demo/Dockerfile b/demo/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..48780cc7c89416e55ade7785abdc288e64f63096 --- /dev/null +++ b/demo/Dockerfile @@ -0,0 +1,70 @@ +# 基础镜像(选手可自由选择) +FROM ac2-registry.cn-hangzhou.cr.aliyuncs.com/ac2/pytorch:2.7.1.8-cuda12.8.1-py312-alinux3.2104 + +# 设置时区(不要改) +ENV TZ=Asia/Shanghai + +# 基础设置(不要改) +RUN set -x && \ + groupadd -g 1000 admin && \ + useradd -u 1000 -g admin -m admin && \ + mkdir -p /home/admin/appspace/atec2026/robot/solution/ && \ + chown -R admin:admin /home/admin/appspace + +# 将镜像自带的 python ac2 虚拟环境所有者改为 admin 用户(选手根据实际情况调整) +RUN chown -R admin:admin /opt/ac2 + +# 设置 pip 源(选手根据实际情况调整) +ENV PIP_INDEX_URL=https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple +ENV PIP_TRUSTED_HOST=mirrors.tuna.tsinghua.edu.cn + +# 使用 admin 用户运行(不要改) +USER admin + +# 工作目录(不要改) +WORKDIR /home/admin/appspace/atec2026/robot + +# 选手的文件都要放到 solution 目录下(不要改) + +# 通用文件:run.sh,requirements.txt,server.py +COPY --chown=admin:admin run.sh ./solution/ +COPY --chown=admin:admin requirements.txt ./solution/ +COPY --chown=admin:admin server.py ./solution/ + +# Task E ACT/XSA submission +COPY --chown=admin:admin solution_act.py ./solution/solution.py +COPY --chown=admin:admin act ./solution/act +COPY --chown=admin:admin policy_act.pt ./solution/policy_act.pt + +# demo2: RL demo +# COPY --chown=admin:admin solution_rl.py ./solution/solution.py +# COPY --chown=admin:admin policy.pt ./solution/ + +# demo3: ACT demo +# COPY --chown=admin:admin solution_act.py ./solution/solution.py +# COPY --chown=admin:admin act ./solution/act +# COPY --chown=admin:admin policy_act.pt ./solution/policy_act.pt + + +# 赋予 run.sh 可执行权限(不要改) +RUN set -x && \ + chmod +x ./solution/run.sh + +# 在工作目录下创建虚拟环境软链接,复用镜像自带的 python ac2 虚拟环境(选手根据实际情况调整) +RUN set -x && \ + ln -s /opt/ac2 venv + +# python 虚拟环境设置,并安装HTTP服务所需依赖(不要改) +RUN set -x && \ + source ./venv/bin/activate && \ + pip install --no-cache-dir fastapi==0.136.0 uvicorn==0.45.0 python-multipart==0.0.26 + +# 依赖安装(选手根据实际情况调整) +RUN set -x && \ + source ./venv/bin/activate && \ + if [ -s "solution/requirements.txt" ]; then \ + pip install --no-cache-dir -r solution/requirements.txt; \ + fi + +# 选手镜像启动命令(不要改) +CMD ["./solution/run.sh"] diff --git a/demo/__init__.py b/demo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/demo/requirements.txt b/demo/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..ebb1520f96adac84ce7fde7b47fd34aeec3769cf --- /dev/null +++ b/demo/requirements.txt @@ -0,0 +1,4 @@ +h5py +fastapi +uvicorn +python-multipart diff --git a/demo/run.sh b/demo/run.sh new file mode 100644 index 0000000000000000000000000000000000000000..d2161227f85fd7bd90e892eeb55a242e049d0dc8 --- /dev/null +++ b/demo/run.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -e +mkdir -p /home/admin/logs/atec2026/robot/solution +cd /home/admin/appspace/atec2026/robot +source ./venv/bin/activate +python solution/server.py 2>&1 | tee /home/admin/logs/atec2026/robot/solution/server.stdout diff --git a/demo/server.py b/demo/server.py new file mode 100644 index 0000000000000000000000000000000000000000..8456fba402735ce19056b76a85c7545f1f970b1b --- /dev/null +++ b/demo/server.py @@ -0,0 +1,166 @@ +from fastapi import FastAPI, Request, Form, File, UploadFile +from fastapi.responses import JSONResponse +import logging +import os +import sys +import signal +import threading +import base64 +import torch +import pickle +import json +from io import BytesIO +import numpy as np +from typing import Optional + +def setup_logging(): + """Setup logging configuration with LOG_DIR environment variable support""" + # default log directory: atec/logs/ + project_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + log_dir = os.environ.get('LOG_DIR', os.path.join(project_dir, 'logs')) + + # Create log directory if it doesn't exist + if not os.path.exists(log_dir): + os.makedirs(log_dir) + + log_file = os.path.join(log_dir, 'user.log') + + # Create module-specific logger + logger = logging.getLogger(__name__) + logger.setLevel(logging.INFO) + + # Create formatter + formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') + + # Create file handler + file_handler = logging.FileHandler(log_file) + file_handler.setFormatter(formatter) + + # Create console handler + console_handler = logging.StreamHandler(sys.stdout) + console_handler.setFormatter(formatter) + + # Add handlers to logger + logger.addHandler(file_handler) + if os.environ.get('LOG_TO_CONSOLE'): + logger.addHandler(console_handler) + + return logger + +# Setup logging +logger = setup_logging() + + +try: + from solution import AlgSolution + agent = AlgSolution() +except Exception as e: + import traceback + logger.error("Failed to initialize AlgSolution: %s", traceback.format_exc()) + exit(-1) + +app = FastAPI() + +logger.info("Server started") + +@app.post('/step') +async def step( + proprio: UploadFile = File(), + extero: Optional[UploadFile] = File(None), + head_rgb: Optional[UploadFile] = File(None), + head_depth: Optional[UploadFile] = File(None), + ee_rgb: UploadFile = File(), + ee_depth: UploadFile = File(), + video_rgb: Optional[UploadFile] = File(None), + video_depth: Optional[UploadFile] = File(None), + current_score: float= Form(), +): + + proprio = torch.tensor(np.frombuffer(await proprio.read(), dtype=np.float32).reshape(1, -1)).cuda() + extero = torch.tensor(np.frombuffer(await extero.read(), dtype=np.float32).reshape(1, -1)).cuda() if extero is not None else None + head_rgb = torch.tensor(np.frombuffer(await head_rgb.read(), dtype=np.uint8).reshape(1, 480, 640, 3)).cuda() if head_rgb is not None else None + head_depth = torch.tensor(np.frombuffer(await head_depth.read(), dtype=np.float32).reshape(1, 480, 640, 1)).cuda() if head_depth is not None else None + video_rgb = torch.tensor(np.frombuffer(await video_rgb.read(), dtype=np.uint8).reshape(1, 480, 640, 3)).cuda() if video_rgb is not None else None + video_depth = torch.tensor(np.frombuffer(await video_depth.read(), dtype=np.float32).reshape(1, 480, 640, 1)).cuda() if video_depth is not None else None + + ee_rgb = torch.tensor(np.frombuffer(await ee_rgb.read(), dtype=np.uint8).reshape(1, 480, 640, 3)).cuda() + ee_depth = torch.tensor(np.frombuffer(await ee_depth.read(), dtype=np.float32).reshape(1, 480, 640, 1)).cuda() + + if head_rgb is not None: + obs = { + 'proprio': proprio, + 'extero': extero, + 'image': { + 'head_rgb': head_rgb, + 'head_depth': head_depth, + 'ee_rgb': ee_rgb, + 'ee_depth': ee_depth, + } + } + else: + obs = { + 'proprio': proprio, + 'extero': extero, + 'image': { + 'video_rgb': video_rgb, + 'video_depth': video_depth, + 'ee_rgb': ee_rgb, + 'ee_depth': ee_depth, + } + } + action = agent.predicts(obs=obs, current_score=current_score) + return action + +@app.post('/reset') +async def reset(request: Request): + form_data = await request.json() + agent.reset(**form_data) + return {"message": "success"} + +@app.get('/synchronize') +async def synchronize(): + return {"message": "success"} + +@app.get('/health') +async def health(): + return {"message": "success"} + + +@app.get('/get_action_spec') +async def get_action_spec(): + if hasattr(agent, 'get_action_spec'): + return agent.get_action_spec() + logger.warning("'get_action_spec' not found in solution") + return {} + + +@app.post('/stop') +async def stop(request: Request): + body = await request.json() + msg = body.get('msg') + logger.info("Stop message received: %s", msg) + return {"message": "success"} + +@app.post('/quit') +async def quit(request: Request): + """Gracefully shutdown the FastAPI application""" + body = await request.json() + msg = body.get('msg', 'quit') + logger.info("Quit message received: %s", msg) + + # Use a timer to shutdown the server after sending response + def shutdown_server(): + import uvicorn + logger.info("Shutting down the server...") + # This will send SIGTERM to the process + os.kill(os.getpid(), signal.SIGTERM) + + # Start shutdown in a separate thread with a small delay to ensure response is sent + shutdown_timer = threading.Timer(1.0, shutdown_server) + shutdown_timer.start() + + return {"message": "Server is shutting down gracefully"} + +if __name__ == '__main__': + import uvicorn + uvicorn.run(app, host='0.0.0.0', port=5000) diff --git a/demo/solution.py b/demo/solution.py new file mode 100644 index 0000000000000000000000000000000000000000..41838bed831d12f21a1034a82765bb4fc3c822ac --- /dev/null +++ b/demo/solution.py @@ -0,0 +1,17 @@ +"""Submission entry point for ATEC Task E. + +The judging server imports `solution.AlgSolution`, so keep this tiny wrapper in +place and put the actual ACT/XSA implementation in `solution_act.py`. +""" + +import os +import sys + +_DEMO_DIR = os.path.dirname(os.path.abspath(__file__)) +if _DEMO_DIR not in sys.path: + sys.path.insert(0, _DEMO_DIR) + +try: + from .solution_act import AlgSolution +except ImportError: + from solution_act import AlgSolution diff --git a/demo/solution_act.py b/demo/solution_act.py new file mode 100644 index 0000000000000000000000000000000000000000..c6b86771adda4c775b1bac87ddc03b179dd75e34 --- /dev/null +++ b/demo/solution_act.py @@ -0,0 +1,292 @@ +import torch +import torch.nn as nn +from collections import deque +import torchvision.transforms.functional as TF +import torchvision.transforms as T +from dataclasses import dataclass +import sys +import os + +current_path = os.path.dirname(os.path.abspath(__file__)) +#sys.path.insert(0, current_path) + +from act.detr.backbone import build_backbone +from act.detr.transformer import build_transformer +from act.detr.detr_vae import build_encoder, DETRVAE + +@dataclass +class Args: + torch_deterministic: bool = True + """if toggled, `torch.backends.cudnn.deterministic=False`""" + cuda: bool = True + """if toggled, cuda will be enabled by default""" + temporal_agg: bool = True + """if toggled, temporal ensembling will be performed at inference""" + + # Backbone + position_embedding: str = 'sine' + backbone: str = 'resnet18' + lr_backbone: float = 1e-5 + masks: bool = False + dilation: bool = False + include_depth: bool = False + """always False — depth not collected; kept for backbone API compatibility""" + include_rgb: bool = True + """use RGB images as input (requires --save_images during collection)""" + + # Transformer + enc_layers: int = 2 + dec_layers: int = 4 + dim_feedforward: int = 512 + hidden_dim: int = 256 + dropout: float = 0.1 + nheads: int = 8 + num_queries: int = 30 + pre_norm: bool = False + use_xsa: bool = False + + +class Agent(nn.Module): + def __init__(self, state_dim: int, act_dim: int, args: Args): + super().__init__() + self.device = 'cuda' + self.state_dim = state_dim + self.act_dim = act_dim + self.normalize = T.Normalize(mean=[0.485, 0.456, 0.406], + std=[0.229, 0.224, 0.225]) + self.include_rgb = args.include_rgb + + # CNN backbone — None for state-only mode (DETRVAE handles both paths) + backbones = [build_backbone(args)] if args.include_rgb else None + + # CVAE decoder + transformer = build_transformer(args) + + # CVAE encoder + encoder = build_encoder(args) + + # ACT ( CVAE encoder + (CNN backbones + CVAE decoder) ) + self.model = DETRVAE( + backbones, + transformer, + encoder, + state_dim=state_dim, + action_dim=act_dim, + num_queries=args.num_queries, + ) + + + + def _preprocess_rgb(self, obs: dict) -> None: + if self.include_rgb and 'rgb' in obs: + obs['rgb'] = obs['rgb'].float() / 255.0 + # obs['rgb']: (B, num_cams, 3, 224, 224) + B, N, C, H, W = obs['rgb'].shape + obs['rgb'] = self.normalize(obs['rgb'].view(B * N, C, H, W)).view(B, N, C, H, W) + + def _model_input(self, obs: dict): + # DETRVAE state-only path expects the state tensor directly, not a dict + return obs if self.include_rgb else obs['state'] + + def get_action(self, obs: dict) -> torch.Tensor: + self._preprocess_rgb(obs) + a_hat, _ = self.model(self._model_input(obs)) + return a_hat + + + +class AlgSolution: + + # Slice into proprio for joint positions (relative to default). + _QPOS_SLICE = slice(0, 8) + _QVEL_SLICE = slice(8, 16) + _RGB_CHANNELS = 3 + _CONCAT_IMAGE_CHANNELS = 8 + + def __init__(self): + self.device = 'cuda' + # Default to the submission-layout policy file, but allow local eval to + # point at a checkpoint without copying 100MB+ files around. + policy_path = os.environ.get("ATEC_ACT_POLICY_PATH", current_path + '/policy_act.pt') + ckpt = torch.load(policy_path, map_location=self.device) + norm_stats = ckpt["norm_stats"] + state_dim = norm_stats["state_mean"].shape[-1] + act_dim = norm_stats["action_mean"].shape[-1] + weight_key = "ema_agent"# if use_ema and "ema_agent" in ckpt else "agent" + + train_args = Args() + model_args = ckpt.get("model_args", {}) + for key in ( + "enc_layers", + "dec_layers", + "dim_feedforward", + "hidden_dim", + "dropout", + "nheads", + "num_queries", + "pre_norm", + "use_xsa", + ): + if key in model_args: + setattr(train_args, key, model_args[key]) + train_args.include_rgb = model_args.get( + "include_rgb", + any("backbone" in k for k in ckpt[weight_key].keys()), + ) + + self.agent = Agent(state_dim, act_dim, train_args).to(self.device) + self.agent.load_state_dict(ckpt[weight_key]) + self.agent.eval() + + self.num_queries = train_args.num_queries + self.temporal_agg = os.environ.get("ATEC_ACT_TEMPORAL_AGG", "1").lower() not in ("0", "false", "no") + self._k = float(os.environ.get("ATEC_ACT_TEMPORAL_K", "0.01")) + self._prefer_new_actions = os.environ.get("ATEC_ACT_PREFER_NEW", "0").lower() in ("1", "true", "yes") + + self.state_mean = norm_stats["state_mean"].to(self.device) # (1, state_dim) + self.state_std = norm_stats["state_std"].to(self.device) # (1, state_dim) + self.act_mean = norm_stats["action_mean"].to(self.device) # (1, act_dim) + self.act_std = norm_stats["action_std"].to(self.device) # (1, act_dim) + + self.default_joint_pos = torch.tensor( + [[0.0, 1.2, -1.5, 0.0, 1.2, 0.0, 0.035, -0.035]], + dtype=torch.float32, + device=self.device, + ) + # Per-episode state + self._ts: int = 0 + self._action_history: deque = deque(maxlen=self.num_queries) + self._last_action_seq: torch.Tensor | None = None + + + startup_zero_steps = 25 + home_qpos_tolerance = 0.10 + home_hold_steps = 5 + + self.teleop_home_joint_pos = torch.tensor( + [[-0.000033, 0.924525, -1.514983, 0.000011, 1.219900, -0.000033, 0.035000, -0.035000]], + dtype=torch.float32, + device=self.device, + ) + + self._startup_zero_steps = max(0, int(startup_zero_steps)) + self._home_qpos_tolerance = float(home_qpos_tolerance) + self._home_hold_steps = max(0, int(home_hold_steps)) + self._home_action = torch.clamp( + (self.teleop_home_joint_pos - self.default_joint_pos) / 0.5, + -1.0, + 1.0, + ) + + self._startup_step = 0 + self._home_stable_steps = 0 + self._home_done = False + + def reset_episode(self): + self._ts = 0 + self._action_history.clear() + self._last_action_seq = None + self._startup_step = 0 + self._home_stable_steps = 0 + self._home_done = False + + def get_action_spec(self): + # Use the official default Task-E Piper action configuration. + return None + + + def _compute_home_action(self, proprio): + joint_pos_rel = proprio[:, self._QPOS_SLICE] + qpos = joint_pos_rel + self.default_joint_pos + qerr = self.teleop_home_joint_pos - qpos + + within_tolerance = torch.all(torch.abs(qerr) <= self._home_qpos_tolerance, dim=1) + self._home_stable_steps = self._home_stable_steps + 1 if bool(torch.all(within_tolerance)) else 0 + + # Env action is a relative joint-position target, not velocity/torque. + # Keep commanding the absolute teleop-home target until the ACT rollout starts. + action = self._home_action.repeat(proprio.shape[0], 1) + home_reached = self._home_stable_steps >= self._home_hold_steps + return action, home_reached + + + def predicts(self, obs, current_score): + if not isinstance(obs, dict) or "proprio" not in obs: + raise ValueError("Expected obs dict with 'proprio' key.") + + proprio = obs["proprio"].to(self.device) # (num_envs, 24) + + # Stage 1: output zero actions for the first few steps. + if self._startup_step < self._startup_zero_steps: + self._startup_step += 1 + return {'action': torch.zeros((proprio.shape[0], self.agent.act_dim)).numpy().tolist(), 'giveup': False} + + # Stage 2: move to teleop_home using only observations. + if not self._home_done: + home_action, home_reached = self._compute_home_action(proprio) + if home_reached: + self._home_done = True + self._ts = 0 + self._action_history.clear() + self._last_action_seq = None + return {'action': home_action.cpu().numpy().tolist(), 'giveup': False} + + # Recover absolute joint positions from relative obs. + joint_pos_rel = proprio[:, self._QPOS_SLICE] # (num_envs, 8) + qpos = joint_pos_rel + self.default_joint_pos # (num_envs, 8) + state = (qpos - self.state_mean) / self.state_std # (num_envs, 8) + model_obs = {"state": state} + + if self.agent.include_rgb: + rgb = obs["image"]["video_rgb"].to(self.device) + if rgb.shape[1] == 4: + rgb = rgb[:, :3] # drop alpha if RGBA/NCHW + if rgb.ndim == 4 and rgb.shape[-1] == 4: + rgb = rgb[..., :3] # drop alpha if RGBA/NHWC + if rgb.dtype != torch.uint8: + rgb = (rgb.float() * 255.0).clamp(0, 255).to(torch.uint8) + if rgb.ndim == 4 and rgb.shape[1] in (3, 4): + pass + else: + rgb = rgb.permute(0, 3, 1, 2) + if rgb.shape[-2:] != (224, 224): + rgb = TF.resize(rgb, [224, 224], + interpolation=TF.InterpolationMode.BILINEAR, + antialias=True) + model_obs["rgb"] = rgb.unsqueeze(1) # (num_envs, 1, 3, 224, 224) uint8 + + ts = self._ts + query_frequency = 1 if self.temporal_agg else self.num_queries + + if ts % query_frequency == 0: + with torch.no_grad(): + action_seq = self.agent.get_action(model_obs) # (num_envs, num_queries, act_dim) + if self.temporal_agg: + self._action_history.append(action_seq) + else: + self._last_action_seq = action_seq + + if self.temporal_agg: + n = len(self._action_history) + # deque[i=0] = oldest (added n-1 steps ago); for current step its offset = n-1-i + actions_for_curr = torch.stack( + [seq[:, n - 1 - i, :] for i, seq in enumerate(self._action_history)], + dim=1, + ) # (num_envs, n, act_dim) + + # Default preserves the original convention. ATECs long-horizon + # rollout can also be evaluated with newer predictions weighted + # higher via ATEC_ACT_PREFER_NEW=1. + order = torch.arange(n, device=self.device) + if self._prefer_new_actions: + order = torch.flip(order, dims=[0]) + exp_weights = torch.exp(-self._k * order) + exp_weights = (exp_weights / exp_weights.sum()).unsqueeze(0).unsqueeze(-1) + raw_action = (actions_for_curr * exp_weights).sum(dim=1) # (num_envs, act_dim) + else: + raw_action = self._last_action_seq[:, ts % query_frequency] # (num_envs, act_dim) + + # Denormalise → env action format + action = raw_action * self.act_std + self.act_mean + self._ts += 1 + return {'action': action.tolist(), 'giveup': False} diff --git a/demo/solution_dual_act.py b/demo/solution_dual_act.py new file mode 100644 index 0000000000000000000000000000000000000000..359f47be6164bcd872b99a36d9deb2201c790f2b --- /dev/null +++ b/demo/solution_dual_act.py @@ -0,0 +1,66 @@ +"""Two-ACT relay experiment for ATEC Task E. + +Both policies are stepped on every observation so their temporal histories stay +aligned with the actual rollout. The primary policy controls the reliable +early phase; after the score reaches the configured band, the secondary policy +may take over the late object_1 phase. +""" + +from __future__ import annotations + +import os + +from solution_act import AlgSolution as _ActSolution + + +class AlgSolution: + def __init__(self): + self._primary_path = os.environ.get("ATEC_DUAL_PRIMARY_POLICY", os.environ.get("ATEC_ACT_POLICY_PATH", "")) + self._secondary_path = os.environ.get("ATEC_DUAL_SECONDARY_POLICY", "") + if not self._secondary_path: + raise RuntimeError("ATEC_DUAL_SECONDARY_POLICY is required for solution_dual_act") + + old_policy_path = os.environ.get("ATEC_ACT_POLICY_PATH") + try: + if self._primary_path: + os.environ["ATEC_ACT_POLICY_PATH"] = self._primary_path + self.primary = _ActSolution() + os.environ["ATEC_ACT_POLICY_PATH"] = self._secondary_path + self.secondary = _ActSolution() + finally: + if old_policy_path is None: + os.environ.pop("ATEC_ACT_POLICY_PATH", None) + else: + os.environ["ATEC_ACT_POLICY_PATH"] = old_policy_path + + self._switch_score = float(os.environ.get("ATEC_DUAL_SWITCH_SCORE", "12.0")) + self._switch_act_steps = int(os.environ.get("ATEC_DUAL_SWITCH_ACT_STEPS", "900")) + self._mode = "primary" + self._step = 0 + + def reset_episode(self): + self.primary.reset_episode() + self.secondary.reset_episode() + self._mode = "primary" + self._step = 0 + + def get_action_spec(self): + return None + + def predicts(self, obs, current_score): + self._step += 1 + primary_resp = self.primary.predicts(obs, current_score) + secondary_resp = self.secondary.predicts(obs, current_score) + primary_steps = int(getattr(self.primary, "_ts", 0)) + if ( + self._mode == "primary" + and float(current_score) >= self._switch_score + and primary_steps >= self._switch_act_steps + ): + self._mode = "secondary" + print( + f"[DUAL_ACT] switching to secondary score={float(current_score):.2f} " + f"primary_steps={primary_steps}", + flush=True, + ) + return secondary_resp if self._mode == "secondary" else primary_resp diff --git a/demo/solution_hybrid_obj1_pca.py b/demo/solution_hybrid_obj1_pca.py new file mode 100644 index 0000000000000000000000000000000000000000..8fb76d20a6ee19970f0df11546e5f38617551194 --- /dev/null +++ b/demo/solution_hybrid_obj1_pca.py @@ -0,0 +1,68 @@ +"""ACT plus object_1-only PCA rescue for Task E experiments. + +This is intentionally conservative: keep the ACT policy in control until the +episode has already reached the 15-point band, then spend remaining time trying +to move object_1 into the basket. It is not the protected submission baseline. +""" + +from __future__ import annotations + +import os + +os.environ.setdefault("ATEC_PCA_OBJECTS", "1") + +from solution_act import AlgSolution as _ActSolution +from solution_pca import AlgSolution as _PcaSolution + + +class AlgSolution: + def __init__(self): + self.act = _ActSolution() + self.pca = _PcaSolution() + self._mode = "act" + self._pca_started = False + self._switch_score = float(os.environ.get("ATEC_HYBRID_SWITCH_SCORE", "15.0")) + self._min_act_policy_steps = int(os.environ.get("ATEC_HYBRID_MIN_ACT_POLICY_STEPS", "900")) + self._force_act_policy_steps = int(os.environ.get("ATEC_HYBRID_FORCE_ACT_POLICY_STEPS", "999999")) + self._force_env_steps = int(os.environ.get("ATEC_HYBRID_FORCE_ENV_STEPS", "999999")) + self._env_steps = 0 + + def reset_episode(self): + self.act.reset_episode() + self.pca.reset_episode() + self._mode = "act" + self._pca_started = False + self._env_steps = 0 + + def get_action_spec(self): + return None + + def _start_pca(self, reason=""): + self.pca.reset_episode() + # ACT has already moved the arm into the workspace. Skip PCA startup + # and home, otherwise the late rescue often times out. + self.pca.t = 25 + self.pca.home_count = 80 + self._mode = "pca" + self._pca_started = True + print(f"[HYBRID] switching to object_1 PCA rescue {reason}".rstrip(), flush=True) + + def predicts(self, obs, current_score): + if self._mode == "act": + self._env_steps += 1 + act_steps = int(getattr(self.act, "_ts", 0)) + score_gate = ( + float(current_score) >= self._switch_score + and act_steps >= self._min_act_policy_steps + ) + act_gate = act_steps >= self._force_act_policy_steps + env_gate = self._env_steps >= self._force_env_steps + if score_gate or act_gate or env_gate: + self._start_pca( + f"score={float(current_score):.2f} act_steps={act_steps} " + f"env_steps={self._env_steps} gate=" + f"{'score' if score_gate else ('act' if act_gate else 'env')}" + ) + else: + return self.act.predicts(obs, current_score) + return self.pca.predicts(obs, current_score) diff --git a/demo/solution_pca.py b/demo/solution_pca.py new file mode 100644 index 0000000000000000000000000000000000000000..b521ba80a3c496eb39ed0beaccfe31cf2b5ae6bb --- /dev/null +++ b/demo/solution_pca.py @@ -0,0 +1,1243 @@ +"""Observation-only GraspGen-style PCA/AABB controller for ATEC Task E. + +This is an experimental submit-style policy: it uses only proprioception plus +the fixed external RGB-D camera observation to estimate object centres, then +drives a calibrated Piper pick/place primitive with local kinematics. +""" + +from __future__ import annotations + +import os +from dataclasses import dataclass + +import numpy as np +import torch + +try: + import pinocchio as pin +except Exception: # pragma: no cover - handled at runtime by the judge/server + pin = None + + +TABLE_CENTER_X = 1.00 +TABLE_CENTER_Y = 0.00 +TABLE_DIMS_AT_0P008 = (0.6468062441005529, 0.9084968693231588, 0.6613141183247961) +TABLE_SCALE = 0.01 +TABLE_DIMS = tuple(dim * (TABLE_SCALE / 0.008) for dim in TABLE_DIMS_AT_0P008) +TABLE_HALF_X = TABLE_DIMS[0] * 0.5 +TABLE_TOP_Z = TABLE_DIMS[2] +BASKET_CENTER_X = TABLE_CENTER_X + 0.08 +BASKET_CENTER_Y = TABLE_CENTER_Y - 0.30 + +DEFAULT_Q = np.array([0.0, 1.2, -1.5, 0.0, 1.2, 0.0, 0.035, -0.035], dtype=np.float64) +HOME_Q = np.array([-0.000033, 0.924525, -1.514983, 0.000011, 1.219900, -0.000033, 0.035, -0.035], dtype=np.float64) +ACTION_SCALE = 0.5 +GRIP_OPEN = np.array([0.035, -0.035], dtype=np.float64) +GRIP_HALF = np.array([0.018, -0.018], dtype=np.float64) +GRIP_CLOSE = np.array([0.0, 0.0], dtype=np.float64) +OBJ1_HOLD_GAP = 0.0415 +OBJ3_HOLD_GAP = float(os.environ.get("ATEC_PCA_OBJ3_HOLD_GAP", "0.0675")) +OBJ3_CLOSE_MIN_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_CLOSE_MIN_STEPS", "160")) +OBJ3_LOW_HOLD_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_LOW_HOLD_STEPS", "0")) +OBJ3_LIFT_CLEARANCE = float(os.environ.get("ATEC_PCA_OBJ3_LIFT_CLEARANCE", "0.12")) +OBJ3_CARRY_CLEARANCE = float(os.environ.get("ATEC_PCA_OBJ3_CARRY_CLEARANCE", "0.145")) +OBJ3_OBJECT_SERVO_GAIN = float(os.environ.get("ATEC_PCA_OBJ3_OBJECT_SERVO_GAIN", "1.0")) +OBJ3_OBJECT_SERVO_MAX_XY = float(os.environ.get("ATEC_PCA_OBJ3_OBJECT_SERVO_MAX_XY", "0.300")) +OBJ3_FINGER_SERVO_MAX_XY = float(os.environ.get("ATEC_PCA_OBJ3_FINGER_SERVO_MAX_XY", "0.240")) +OBJ3_APPROACH_FINGER_Z = float(os.environ.get("ATEC_PCA_OBJ3_APPROACH_FINGER_Z", str(TABLE_TOP_Z + 0.090))) +OBJ3_CLOSE_FINGER_Z = float(os.environ.get("ATEC_PCA_OBJ3_CLOSE_FINGER_Z", str(TABLE_TOP_Z + 0.000))) +OBJ3_LIFT_FINGER_Z = float(os.environ.get("ATEC_PCA_OBJ3_LIFT_FINGER_Z", str(TABLE_TOP_Z + 0.045))) +OBJ3_ENABLE_INSERT = os.environ.get("ATEC_PCA_OBJ3_ENABLE_INSERT", "0") != "0" +OBJ3_PREGRASP_OFFSET = np.array( + [ + float(os.environ.get("ATEC_PCA_OBJ3_PREGRASP_X_OFFSET", "0.000")), + float(os.environ.get("ATEC_PCA_OBJ3_PREGRASP_Y_OFFSET", "0.080")), + ], + dtype=np.float64, +) +OBJ3_SIDE_APPROACH_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_SIDE_APPROACH_STEPS", "160")) +OBJ3_SIDE_LOW_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_SIDE_LOW_STEPS", "140")) +OBJ3_INSERT_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_INSERT_STEPS", "220")) +OBJ3_PREGRASP_LOW_FINGER_Z = float(os.environ.get("ATEC_PCA_OBJ3_PREGRASP_LOW_FINGER_Z", str(TABLE_TOP_Z + 0.024))) +OBJ3_FALLBACK_DRAG_Z = float(os.environ.get("ATEC_PCA_OBJ3_FALLBACK_DRAG_Z", str(TABLE_TOP_Z + 0.035))) +OBJ3_FALLBACK_START_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_FALLBACK_START_STEPS", "60")) +OBJ3_FALLBACK_MID_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_FALLBACK_MID_STEPS", "260")) +OBJ3_FALLBACK_END_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_FALLBACK_END_STEPS", "260")) +OBJ3_FALLBACK_OPEN_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_FALLBACK_OPEN_STEPS", "100")) +OBJ3_DRAG_START_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_DRAG_START_STEPS", "80")) +OBJ3_DRAG_MID_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_DRAG_MID_STEPS", "360")) +OBJ3_DRAG_END_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_DRAG_END_STEPS", "360")) +OBJ3_DRAG_SETTLE_STEPS = int(os.environ.get("ATEC_PCA_OBJ3_DRAG_SETTLE_STEPS", "120")) +PCA_DLS_MAX_DELTA = float(os.environ.get("ATEC_PCA_DLS_MAX_DELTA", "0.18")) +PCA_FINGER_IK_MAX_DELTA = float(os.environ.get("ATEC_PCA_FINGER_IK_MAX_DELTA", "0.18")) +OBJ3_GRIPPER_MAX_DELTA = float(os.environ.get("ATEC_PCA_OBJ3_GRIPPER_MAX_DELTA", "0.003")) +OBJ3_HOLD_GRIP_DEFAULT = np.array( + [ + float(os.environ.get("ATEC_PCA_OBJ3_HOLD_Q_POS", "0.0000")), + float(os.environ.get("ATEC_PCA_OBJ3_HOLD_Q_NEG", "0.0000")), + ], + dtype=np.float64, +) + +BASE_POS_W = np.array([TABLE_CENTER_X + TABLE_HALF_X, TABLE_CENTER_Y, TABLE_TOP_Z], dtype=np.float64) +R_W_B = np.diag([-1.0, -1.0, 1.0]) +K_VIDEO = np.array([[732.99927, 0.0, 320.0], [0.0, 732.99927, 240.0], [0.0, 0.0, 1.0]], dtype=np.float64) +CAM_POS_W = np.array([-0.2, 0.0, 1.6266427], dtype=np.float64) +CAM_QUAT_WXYZ = np.array([-0.33350849, 0.62351596, -0.62351584, 0.33350849], dtype=np.float64) + +OBJ_Y_BANDS = { + 1: (TABLE_CENTER_Y + 0.25, TABLE_CENTER_Y + 0.29), + 2: (TABLE_CENTER_Y + 0.14, TABLE_CENTER_Y + 0.20), + 3: (TABLE_CENTER_Y + 0.03, TABLE_CENTER_Y + 0.09), +} +OBJ_Z_LIMITS = { + 1: (TABLE_TOP_Z + 0.035, TABLE_TOP_Z + 0.130), + 2: (TABLE_TOP_Z + 0.020, TABLE_TOP_Z + 0.190), + 3: (TABLE_TOP_Z + 0.012, TABLE_TOP_Z + 0.095), +} +OBJ_GRASP_CENTER_OFFSETS = { + 1: np.array([0.0, 0.0], dtype=np.float64), + 2: np.array([0.060, 0.0], dtype=np.float64), + 3: np.array([float(os.environ.get("ATEC_PCA_OBJ3_X_OFFSET", "0.0")), 0.0], dtype=np.float64), +} +OBJ_CENTER_COMPLETION_OFFSETS = { + # The fixed camera sees object_1 from the lower-y side when it is near the + # top band edge; RGB-D AABB/median centres land on the visible side instead + # of the root/contact centre. This completes the centre before applying + # the Piper finger offset below. + 1: np.array([0.020, 0.0], dtype=np.float64), + 2: np.array([0.0, 0.0], dtype=np.float64), + 3: np.array( + [ + 0.0, + float(os.environ.get("ATEC_PCA_OBJ3_CENTER_Y_OFFSET", "0.000")), + ], + dtype=np.float64, + ), +} +OBJ_TCP_Z = {1: 0.140, 2: 0.040, 3: 0.090} +OBJ_CLOSE_Z_OFFSETS = {1: 0.020, 2: 0.020, 3: float(os.environ.get("ATEC_PCA_OBJ3_CLOSE_Z_OFFSET", "-0.005"))} +OBJ_CLOSE_Z = { + 1: TABLE_TOP_Z + 0.030, # low close plane; compensate submit IK's high-contact bias + 2: TABLE_TOP_Z + 0.030, + 3: TABLE_TOP_Z + 0.030, +} +OBJ_ROOT_Z_EST = { + 1: TABLE_TOP_Z + 0.045, + 2: TABLE_TOP_Z + 0.055, + 3: TABLE_TOP_Z + 0.035, +} +OBJ_PRECLOSE_INSERT_OFFSETS = { + 1: np.array([0.0, 0.0], dtype=np.float64), +} +OBJ_FINGER_XY_OFFSETS = { + # Calibrated from successful 2026-05-20 scripted traces. Banana succeeds + # when the actual link7/link8 centre is slightly on the -X side of the + # object root, cradling the curve instead of pushing from the +X side. + 3: np.array( + [ + float(os.environ.get("ATEC_PCA_OBJ3_FINGER_X_OFFSET", "-0.010")), + float(os.environ.get("ATEC_PCA_OBJ3_FINGER_Y_OFFSET", "0.000")), + ], + dtype=np.float64, + ), +} +OBJ_FINGER_TARGET_REL_Z = { + 1: -0.025, + 3: float(os.environ.get("ATEC_PCA_OBJ3_FINGER_REL_Z", "0.027")), +} +OBJ_FINGER_SERVO_MAX_Z = {1: 0.050, 3: 0.040} +OBJ_REACH_STEPS = {1: 200, 2: 200, 3: 200} +OBJ_CLOSE_STEPS = {1: 220, 2: 180, 3: int(os.environ.get("ATEC_PCA_OBJ3_CLOSE_STEPS", "90"))} +OBJ_LIFT_STEPS = {1: 300, 2: 200, 3: int(os.environ.get("ATEC_PCA_OBJ3_LIFT_STEPS", "35"))} +OBJ_TRANSPORT_STEPS = {1: 1400, 2: 1400, 3: int(os.environ.get("ATEC_PCA_OBJ3_TRANSPORT_STEPS", "440"))} +OBJ_PLACE_STEPS = {1: 260, 2: 260, 3: 220} +OBJ_OPEN_STEPS = {1: 260, 2: 260, 3: 220} +OBJ_PLACE_XY_OFFSETS = { + 1: np.array([0.0, 0.0], dtype=np.float64), + 3: np.array( + [ + float(os.environ.get("ATEC_PCA_OBJ3_PLACE_X_OFFSET", "0.0")), + float(os.environ.get("ATEC_PCA_OBJ3_PLACE_Y_OFFSET", "0.0")), + ], + dtype=np.float64, + ), +} + + +def _quat_wxyz_to_rot(q: np.ndarray) -> np.ndarray: + q = np.asarray(q, dtype=np.float64) + q = q / max(np.linalg.norm(q), 1e-12) + w, x, y, z = q + return np.array( + [ + [1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)], + [2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)], + [2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)], + ], + dtype=np.float64, + ) + + +def _rot_error(current: np.ndarray, target: np.ndarray) -> np.ndarray: + err = target @ current.T + return 0.5 * np.array( + [err[2, 1] - err[1, 2], err[0, 2] - err[2, 0], err[1, 0] - err[0, 1]], + dtype=np.float64, + ) + + +def _world_to_base_pos(pos_w: np.ndarray) -> np.ndarray: + return R_W_B.T @ (np.asarray(pos_w, dtype=np.float64) - BASE_POS_W) + + +def _world_to_base_rot(rot_w: np.ndarray) -> np.ndarray: + return R_W_B.T @ rot_w + + +@dataclass +class PoseTarget: + pos_w: np.ndarray + rot_w: np.ndarray + grip: np.ndarray + steps: int + finger_xy: np.ndarray | None = None + finger_z: float | None = None + servo_obj_z: float | None = None + servo_target_rel_z: float | None = None + freeze_arm: bool = False + label: str = "" + + +class _PiperIK: + def __init__(self): + if pin is None: + raise RuntimeError("pinocchio is required for solution_pca.py") + root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + urdf = os.path.join(root, "third_party", "Agilex-College", "piper", "handpose_det", "models", "modified_piper_without_camera.urdf") + if not os.path.exists(urdf): + urdf = os.environ.get("ATEC_PIPER_URDF", urdf) + self.model = pin.buildModelFromUrdf(urdf) + self.data = self.model.createData() + self.frame_id = self.model.getFrameId("gripper_base") + self.link7_id = self.model.getFrameId("link7") + self.link8_id = self.model.getFrameId("link8") + self._last_q = HOME_Q[:6].copy() + + def fk_base(self, q6: np.ndarray): + q = np.concatenate([np.asarray(q6, dtype=np.float64), GRIP_OPEN]) + pin.forwardKinematics(self.model, self.data, q) + pin.updateFramePlacements(self.model, self.data) + M = self.data.oMf[self.frame_id] + return M.translation.copy(), M.rotation.copy() + + def solve(self, q_current8: np.ndarray, pos_w: np.ndarray, rot_w: np.ndarray) -> np.ndarray: + target_pos_b = _world_to_base_pos(pos_w) + target_rot_b = _world_to_base_rot(rot_w) + q6 = np.asarray(q_current8[:6], dtype=np.float64).copy() + if not np.all(np.isfinite(q6)): + q6 = self._last_q.copy() + for _ in range(35): + pos_b, rot_b = self.fk_base(q6) + err = np.concatenate([target_pos_b - pos_b, _rot_error(rot_b, target_rot_b)]) + if np.linalg.norm(err[:3]) < 0.003 and np.linalg.norm(err[3:]) < 0.03: + break + J = pin.computeFrameJacobian( + self.model, + self.data, + np.concatenate([q6, GRIP_OPEN]), + self.frame_id, + pin.ReferenceFrame.LOCAL_WORLD_ALIGNED, + )[:, :6] + damping = 0.020 + dq = J.T @ np.linalg.solve(J @ J.T + damping * damping * np.eye(6), err) + dq = np.clip(dq, -0.20, 0.20) + q6 = np.clip(q6 + dq, [-2.618, 0.0, -2.967, -1.745, -1.22, -2.0944], [2.618, 3.14, 0.0, 1.745, 1.22, 2.0944]) + # Near contact, being centimetres high is worse than a small wrist + # orientation error. The successful simulator runner effectively + # servos the link7/link8 centre every step; this position-only cleanup + # gives the submit-style IK the same priority. + for _ in range(20): + pos_b, _ = self.fk_base(q6) + pos_err = target_pos_b - pos_b + if np.linalg.norm(pos_err) < 0.002: + break + J = pin.computeFrameJacobian( + self.model, + self.data, + np.concatenate([q6, GRIP_OPEN]), + self.frame_id, + pin.ReferenceFrame.LOCAL_WORLD_ALIGNED, + )[:3, :6] + damping = 0.012 + dq = J.T @ np.linalg.solve(J @ J.T + damping * damping * np.eye(3), pos_err) + dq = np.clip(dq, -0.18, 0.18) + q6 = np.clip(q6 + dq, [-2.618, 0.0, -2.967, -1.745, -1.22, -2.0944], [2.618, 3.14, 0.0, 1.745, 1.22, 2.0944]) + self._last_q = q6.copy() + return q6 + + def step_dls( + self, + q_current8: np.ndarray, + pos_w: np.ndarray, + rot_w: np.ndarray, + *, + lambda_val: float = 0.05, + max_joint_delta: float = PCA_DLS_MAX_DELTA, + position_only: bool = False, + ) -> np.ndarray: + """One DifferentialIK-style DLS update from the current joint state. + + The successful simulator runner uses IsaacLab's CartesianController, + which computes a small damped least-squares update from the current + PhysX state on every frame. This mirrors that behavior more closely + than solving a full IK target and then clipping the final joint target. + """ + target_pos_b = _world_to_base_pos(pos_w) + target_rot_b = _world_to_base_rot(rot_w) + q6 = np.asarray(q_current8[:6], dtype=np.float64).copy() + if not np.all(np.isfinite(q6)): + q6 = self._last_q.copy() + q8 = np.concatenate([q6, GRIP_OPEN]) + pos_b, rot_b = self.fk_base(q6) + J_full = pin.computeFrameJacobian( + self.model, + self.data, + q8, + self.frame_id, + pin.ReferenceFrame.LOCAL_WORLD_ALIGNED, + )[:, :6] + if position_only: + err = target_pos_b - pos_b + J = J_full[:3, :] + else: + err = np.concatenate([target_pos_b - pos_b, _rot_error(rot_b, target_rot_b)]) + J = J_full + damping = float(lambda_val) + dq = J.T @ np.linalg.solve(J @ J.T + damping * damping * np.eye(J.shape[0]), err) + dq = np.clip(dq, -max_joint_delta, max_joint_delta) + q6 = np.clip( + q6 + dq, + [-2.618, 0.0, -2.967, -1.745, -1.22, -2.0944], + [2.618, 3.14, 0.0, 1.745, 1.22, 2.0944], + ) + self._last_q = q6.copy() + return q6 + + def finger_center_world(self, q_current8: np.ndarray) -> np.ndarray: + q = np.asarray(q_current8, dtype=np.float64).copy() + pin.forwardKinematics(self.model, self.data, q) + pin.updateFramePlacements(self.model, self.data) + p7 = self.data.oMf[self.link7_id].translation + p8 = self.data.oMf[self.link8_id].translation + center_b = 0.5 * (p7 + p8) + return BASE_POS_W + R_W_B @ center_b + + def finger_gap(self, q_current8: np.ndarray) -> float: + q = np.asarray(q_current8, dtype=np.float64).copy() + pin.forwardKinematics(self.model, self.data, q) + pin.updateFramePlacements(self.model, self.data) + p7 = self.data.oMf[self.link7_id].translation + p8 = self.data.oMf[self.link8_id].translation + return float(np.linalg.norm(p7 - p8)) + + def solve_finger(self, q_current8: np.ndarray, finger_w: np.ndarray, rot_w: np.ndarray) -> np.ndarray: + """IK on the actual link7/link8 centre, not the gripper_base proxy.""" + target_pos_b = _world_to_base_pos(finger_w) + target_rot_b = _world_to_base_rot(rot_w) + q_current8 = np.asarray(q_current8, dtype=np.float64).copy() + q6 = q_current8[:6].copy() + grip = q_current8[6:8].copy() + if not np.all(np.isfinite(q6)): + q6 = self._last_q.copy() + for _ in range(40): + q8 = np.concatenate([q6, grip]) + pin.forwardKinematics(self.model, self.data, q8) + pin.updateFramePlacements(self.model, self.data) + p7 = self.data.oMf[self.link7_id].translation + p8 = self.data.oMf[self.link8_id].translation + center_b = 0.5 * (p7 + p8) + gb_rot = self.data.oMf[self.frame_id].rotation + pos_err = target_pos_b - center_b + rot_err = _rot_error(gb_rot, target_rot_b) + if np.linalg.norm(pos_err) < 0.002 and np.linalg.norm(rot_err) < 0.05: + break + J7 = pin.computeFrameJacobian(self.model, self.data, q8, self.link7_id, pin.ReferenceFrame.LOCAL_WORLD_ALIGNED)[:3, :6] + J8 = pin.computeFrameJacobian(self.model, self.data, q8, self.link8_id, pin.ReferenceFrame.LOCAL_WORLD_ALIGNED)[:3, :6] + Jpos = 0.5 * (J7 + J8) + Jrot = pin.computeFrameJacobian(self.model, self.data, q8, self.frame_id, pin.ReferenceFrame.LOCAL_WORLD_ALIGNED)[3:, :6] + rot_wt = 0.05 + J = np.vstack([Jpos, rot_wt * Jrot]) + err = np.concatenate([pos_err, rot_wt * rot_err]) + damping = 0.018 + dq = J.T @ np.linalg.solve(J @ J.T + damping * damping * np.eye(6), err) + dq = np.clip(dq, -PCA_FINGER_IK_MAX_DELTA, PCA_FINGER_IK_MAX_DELTA) + q6 = np.clip(q6 + dq, [-2.618, 0.0, -2.967, -1.745, -1.22, -2.0944], [2.618, 3.14, 0.0, 1.745, 1.22, 2.0944]) + self._last_q = q6.copy() + return q6 + + +class AlgSolution: + def __init__(self): + self.device = "cuda" if torch.cuda.is_available() else "cpu" + self.ik = _PiperIK() + self.reset() + + def reset(self, **_kwargs): + self.t = 0 + self.home_count = 0 + self.plan: list[PoseTarget] = [] + self.plan_idx = 0 + self.step_in_target = 0 + self.detected = False + self.fallback_done = False + self.objects: tuple[int, ...] = () + self._last_action = np.zeros(8, dtype=np.float64) + self._obj1_hold_grip: np.ndarray | None = None + self._obj3_hold_grip: np.ndarray | None = None + self._obj3_carry_offset_xy: np.ndarray | None = None + self._detected_centers: dict[int, np.ndarray] = {} + + def reset_episode(self): + self.reset() + + def _obs_qpos(self, obs: dict) -> np.ndarray: + proprio = obs["proprio"] + if isinstance(proprio, torch.Tensor): + p = proprio.detach().cpu().numpy()[0] + else: + p = np.asarray(proprio)[0] + return p[:8].astype(np.float64) + DEFAULT_Q + + def _video_rgb_depth(self, obs: dict) -> tuple[np.ndarray, np.ndarray]: + rgb = obs["image"]["video_rgb"] + if isinstance(rgb, torch.Tensor): + rgb_arr = rgb.detach().cpu().numpy()[0] + else: + rgb_arr = np.asarray(rgb)[0] + if rgb_arr.ndim == 3 and rgb_arr.shape[0] in (3, 4): + rgb_arr = np.transpose(rgb_arr[:3], (1, 2, 0)) + if rgb_arr.shape[-1] == 4: + rgb_arr = rgb_arr[..., :3] + if np.issubdtype(rgb_arr.dtype, np.floating): + rgb_arr = (rgb_arr * 255.0).clip(0, 255).astype(np.uint8) + + depth = obs["image"]["video_depth"] + if isinstance(depth, torch.Tensor): + arr = depth.detach().cpu().numpy()[0] + else: + arr = np.asarray(depth)[0] + if arr.ndim == 3: + arr = arr[..., 0] + return rgb_arr.astype(np.uint8, copy=False), arr.astype(np.float64) + + def _points_for_object( + self, + rgb: np.ndarray, + depth: np.ndarray, + obj_idx: int, + *, + wide: bool = False, + fill_holes: bool = True, + ) -> np.ndarray: + h, w = depth.shape + ys, xs = np.where(np.isfinite(depth) & (depth > 0.0) & (depth < 6.0)) + if len(xs) == 0: + return np.zeros((0, 3), dtype=np.float64) + z = depth[ys, xs] + x = (xs.astype(np.float64) - K_VIDEO[0, 2]) / K_VIDEO[0, 0] * z + y = (ys.astype(np.float64) - K_VIDEO[1, 2]) / K_VIDEO[1, 1] * z + pts_cam = np.stack([x, y, z], axis=1) + rot_w_cam = _quat_wxyz_to_rot(CAM_QUAT_WXYZ) + pts = (rot_w_cam @ pts_cam.T).T + CAM_POS_W + y0, y1 = OBJ_Y_BANDS[obj_idx] + if wide: + y0 = BASKET_CENTER_Y - 0.10 + y1 = OBJ_Y_BANDS[obj_idx][1] + (0.045 if obj_idx == 3 else 0.10) + z0, z1 = OBJ_Z_LIMITS[obj_idx] + if wide: + z0 = TABLE_TOP_Z + 0.005 + if obj_idx == 3: + z1 = TABLE_TOP_Z + 0.220 + rgb_pts = rgb[ys, xs].astype(np.float32) + maxc = rgb_pts.max(axis=1) + minc = rgb_pts.min(axis=1) + non_gray = ((maxc - minc) > 18.0) | (maxc > 170.0) + if obj_idx == 3: + # Use the banana's yellow appearance for dynamic tracking. The broad + # world band can include the pink basket, white gripper, and mustard; + # a simple color gate is more reliable than generic non-gray there. + r, g, b = rgb_pts[:, 0], rgb_pts[:, 1], rgb_pts[:, 2] + non_gray = (r > 105.0) & (g > 75.0) & (b < 130.0) & ((r - b) > 35.0) + keep = ( + (pts[:, 0] >= TABLE_CENTER_X - 0.18) + & (pts[:, 0] <= TABLE_CENTER_X + 0.18) + & (pts[:, 1] >= y0 - 0.035) + & (pts[:, 1] <= y1 + 0.035) + & (pts[:, 2] >= z0) + & (pts[:, 2] <= z1) + & non_gray + ) + if np.count_nonzero(keep) == 0: + return pts[keep] + if not fill_holes: + return pts[keep] + # Mirror rgbd_band_object_mask(): fill shallow holes inside the detected + # component ROI, still constrained by the legal world band and z gate. + yy = ys[keep] + xx = xs[keep] + x1, x2 = int(xx.min()), int(xx.max()) + y1p, y2p = int(yy.min()), int(yy.max()) + in_roi = (xs >= x1) & (xs <= x2) & (ys >= y1p) & (ys <= y2p) + fill_keep = ( + in_roi + & (pts[:, 0] >= TABLE_CENTER_X - 0.18) + & (pts[:, 0] <= TABLE_CENTER_X + 0.18) + & (pts[:, 1] >= y0 - 0.035) + & (pts[:, 1] <= y1 + 0.035) + & (pts[:, 2] >= z0) + & (pts[:, 2] <= z1) + ) + return pts[fill_keep] + + def _estimate_grasp(self, rgb: np.ndarray, depth: np.ndarray, obj_idx: int, *, wide: bool = False) -> tuple[np.ndarray, np.ndarray]: + pts = self._points_for_object(rgb, depth, obj_idx, wide=wide, fill_holes=(obj_idx != 1)) + if len(pts) < 64: + # Spawn-band fallback keeps the controller alive if one frame is bad. + y0, y1 = OBJ_Y_BANDS[obj_idx] + center = np.array([TABLE_CENTER_X, 0.5 * (y0 + y1), TABLE_TOP_Z + 0.06], dtype=np.float64) + return center, _quat_wxyz_to_rot(np.array([0.0, 1.0, 0.0, 0.0], dtype=np.float64)) + center = pts.mean(axis=0) + world_aabb_center = 0.5 * (pts.min(axis=0) + pts.max(axis=0)) + cov = (pts - center).T @ (pts - center) / max(len(pts) - 1, 1) + vals, vecs = np.linalg.eigh(cov) + order = np.argsort(vals)[::-1] + axes = vecs[:, order] + if np.linalg.det(axes) < 0: + axes[:, 2] *= -1 + local = (axes.T @ (pts - center).T).T + mn, mx = local.min(axis=0), local.max(axis=0) + aabb_center = axes @ ((mn + mx) * 0.5) + center + extents = mx - mn + if obj_idx == 3: + exec_center = aabb_center.copy() + # The banana is curved; when the visible PCA/AABB centre drifts + # toward the far end of the crescent, the calibrated -X finger + # offset is cancelled and the gripper closes on the outside. In + # that case the RGB-D point mean is a better proxy for the contact + # root used by the successful runner traces. + if abs(float(aabb_center[0] - center[0])) > float(os.environ.get("ATEC_PCA_OBJ3_AABB_MEAN_X_SWITCH", "0.025")): + exec_center[0] = center[0] + float(os.environ.get("ATEC_PCA_OBJ3_MEAN_X_BIAS", "0.005")) + else: + upper = pts[pts[:, 2] >= np.percentile(pts[:, 2], 70)] + # Object 1/2 visible-surface medians can be biased toward the + # camera-facing side by 2+ cm. Use the world AABB centre for XY + # completion, while keeping a high visible-surface z for approach. + exec_center = world_aabb_center.copy() + z_src = upper if len(upper) else pts + exec_center[2] = float(np.percentile(z_src[:, 2], 85)) + if os.environ.get("ATEC_PCA_DEBUG_TARGET"): + upper = pts[pts[:, 2] >= np.percentile(pts[:, 2], 70)] + upper_med = np.median(upper if len(upper) else pts, axis=0) + print( + f"[PCA_EST] obj={obj_idx} n={len(pts)} " + f"mean=({center[0]:.3f},{center[1]:.3f},{center[2]:.3f}) " + f"world_aabb=({world_aabb_center[0]:.3f},{world_aabb_center[1]:.3f},{world_aabb_center[2]:.3f}) " + f"upper_med=({upper_med[0]:.3f},{upper_med[1]:.3f},{upper_med[2]:.3f}) " + f"exec=({exec_center[0]:.3f},{exec_center[1]:.3f},{exec_center[2]:.3f})", + flush=True, + ) + + grasp_axis = int(np.argmin(extents)) + if grasp_axis == 0: + jaw_hint_w = axes[:, 1] + else: + jaw_hint_w = axes[:, 0] + jaw_xy = np.array([jaw_hint_w[0], jaw_hint_w[1], 0.0], dtype=np.float64) + if np.linalg.norm(jaw_xy) < 1e-6: + jaw_xy = np.array([0.0, 1.0, 0.0], dtype=np.float64) + jaw_xy /= np.linalg.norm(jaw_xy) + grip_z = np.array([0.0, 0.0, -1.0], dtype=np.float64) + align_x = np.cross(jaw_xy, grip_z) + align_x /= max(np.linalg.norm(align_x), 1e-6) + jaw_y = np.cross(grip_z, align_x) + jaw_y /= max(np.linalg.norm(jaw_y), 1e-6) + rot_w_tool = np.stack([align_x, jaw_y, grip_z], axis=1) + return exec_center.astype(np.float64), rot_w_tool.astype(np.float64) + + def _estimate_object3_current_center(self, obs: dict) -> np.ndarray | None: + rgb, depth = self._video_rgb_depth(obs) + pts = self._points_for_object(rgb, depth, 3, wide=True, fill_holes=True) + if len(pts) < 64: + return None + center = 0.5 * (pts.min(axis=0) + pts.max(axis=0)) + # Track the table-near/lifted banana body, not high gripper occluders. + center[2] = float(np.percentile(pts[:, 2], 65)) + center[:2] += OBJ_CENTER_COMPLETION_OFFSETS[3] + if not np.all(np.isfinite(center)): + return None + if not (TABLE_CENTER_X - 0.22 <= center[0] <= TABLE_CENTER_X + 0.22): + return None + if not (BASKET_CENTER_Y - 0.14 <= center[1] <= OBJ_Y_BANDS[3][1] + 0.10): + return None + return center.astype(np.float64) + + def _build_object3_drag_fallback(self, obs: dict) -> bool: + topdown = _quat_wxyz_to_rot(np.array([0.0, 1.0, 0.0, 0.0], dtype=np.float64)) + # Re-localize the banana at fallback time. Use the same narrow + # closed-drag recovery that succeeded in run_graspnet_pick.py: keep the + # gripper closed and drag from the current object centre to the basket + # centre in two smooth segments. + drag_z = OBJ3_FALLBACK_DRAG_Z + c_live = self._estimate_object3_current_center(obs) + c0 = c_live if c_live is not None else self._detected_centers.get( + 3, np.array([TABLE_CENTER_X, OBJ_Y_BANDS[3][0], TABLE_TOP_Z], dtype=np.float64) + ) + start = np.array([c0[0], c0[1], drag_z], dtype=np.float64) + mid = np.array([BASKET_CENTER_X, 0.5 * (c0[1] + BASKET_CENTER_Y), drag_z], dtype=np.float64) + end = np.array([BASKET_CENTER_X, BASKET_CENTER_Y, drag_z], dtype=np.float64) + print( + f"[PCA_FALLBACK] object_3 closed_drag cur=({c0[0]:.3f},{c0[1]:.3f},{c0[2]:.3f}) " + f"mid=({mid[0]:.3f},{mid[1]:.3f},{mid[2]:.3f}) " + f"end=({end[0]:.3f},{end[1]:.3f},{end[2]:.3f})", + flush=True, + ) + self.plan = [] + self.plan_idx = 0 + self.step_in_target = 0 + hold_grip = self._obj3_hold_grip.copy() if self._obj3_hold_grip is not None else OBJ3_HOLD_GRIP_DEFAULT.copy() + finger_offset = OBJ_FINGER_XY_OFFSETS[3] + start_finger = start[:2] + finger_offset + mid_finger = mid[:2] + finger_offset + end_finger = end[:2] + finger_offset + self._add_pose([start_finger[0], start_finger[1], drag_z], topdown, hold_grip, OBJ3_FALLBACK_START_STEPS, finger_xy=start_finger, finger_z=drag_z, label="fallback_closed_drag_start") + self._add_pose([mid_finger[0], mid_finger[1], drag_z], topdown, hold_grip, OBJ3_FALLBACK_MID_STEPS, finger_xy=mid_finger, finger_z=drag_z, label="fallback_closed_drag_mid") + self._add_pose([end_finger[0], end_finger[1], drag_z], topdown, hold_grip, OBJ3_FALLBACK_END_STEPS, finger_xy=end_finger, finger_z=drag_z, label="fallback_closed_drag_end") + self._add_pose([end_finger[0], end_finger[1], drag_z], topdown, GRIP_OPEN, OBJ3_FALLBACK_OPEN_STEPS, finger_xy=end_finger, finger_z=drag_z, label="fallback_closed_drag_open") + self._add_pose([BASKET_CENTER_X, BASKET_CENTER_Y, TABLE_TOP_Z + 0.18], topdown, GRIP_OPEN, 120, label="fallback_retract") + return True + + def _build_object1_drag_rescue(self, obs: dict) -> bool: + rgb, depth = self._video_rgb_depth(obs) + pts = self._points_for_object(rgb, depth, 1, wide=True, fill_holes=False) + if len(pts) < 64: + print(f"[PCA_RESCUE] skip object_1 drag: only {len(pts)} points", flush=True) + return False + # After transport failures object_1 is usually back on the table. The + # high visible points can be the gripper/finger occluder or a lifted + # face, so estimate the rescue push centre from table-near points only. + low = pts[(pts[:, 2] >= TABLE_TOP_Z + 0.030) & (pts[:, 2] <= TABLE_TOP_Z + 0.110)] + if len(low) >= 32: + c = 0.5 * (low.min(axis=0) + low.max(axis=0)) + c[2] = float(np.median(low[:, 2])) + else: + c, _ = self._estimate_grasp(rgb, depth, 1, wide=True) + if not np.all(np.isfinite(c)): + return False + topdown = _quat_wxyz_to_rot(np.array([0.0, 1.0, 0.0, 0.0], dtype=np.float64)) + drag_z = TABLE_TOP_Z + 0.055 + # Push from the object's positive-y side toward the basket. A fixed + # start_y misses the cube after ACT/hybrid rollouts because object_1 + # often remains around y=0.26..0.34. + lanes_x = [ + float(np.clip(c[0] - 0.045, TABLE_CENTER_X - 0.16, TABLE_CENTER_X + 0.22)), + float(np.clip(c[0], TABLE_CENTER_X - 0.16, TABLE_CENTER_X + 0.22)), + float(np.clip(c[0] + 0.045, TABLE_CENTER_X - 0.16, TABLE_CENTER_X + 0.22)), + ] + start_y = float(np.clip(c[1] + 0.085, TABLE_CENTER_Y + 0.085, TABLE_CENTER_Y + 0.46)) + end_y = BASKET_CENTER_Y + print( + f"[PCA_RESCUE] object_1 drag c=({c[0]:.3f},{c[1]:.3f},{c[2]:.3f}) " + f"low_n={len(low)} " + f"lanes={','.join(f'{x:.2f}' for x in lanes_x)} y=({start_y:.3f}->{end_y:.3f})", + flush=True, + ) + self.objects = (1,) + self.plan = [] + self.plan_idx = 0 + self.step_in_target = 0 + for i, lane_x in enumerate(lanes_x): + start = np.array([lane_x, start_y, drag_z], dtype=np.float64) + end = np.array([lane_x, end_y, drag_z], dtype=np.float64) + self._add_pose([lane_x, start_y, TABLE_TOP_Z + 0.20], topdown, GRIP_OPEN, 70, label=f"obj1_rescue_lane{i}_pre") + self._add_pose(start, topdown, GRIP_OPEN, 100, finger_xy=start[:2], finger_z=drag_z, label=f"obj1_rescue_lane{i}_start") + self._add_pose(end, topdown, GRIP_OPEN, 520, finger_xy=end[:2], finger_z=drag_z, label=f"obj1_rescue_lane{i}_mid") + self._add_pose([BASKET_CENTER_X, BASKET_CENTER_Y, TABLE_TOP_Z + 0.15], topdown, GRIP_OPEN, 160, label="obj1_rescue_open") + self._add_pose([RETRACT_X, RETRACT_Y, TABLE_TOP_Z + 0.40], topdown, GRIP_OPEN, 80, label="obj1_rescue_retract") + return True + + def _build_plan(self, obs: dict): + rgb, depth = self._video_rgb_depth(obs) + topdown = _quat_wxyz_to_rot(np.array([0.0, 1.0, 0.0, 0.0], dtype=np.float64)) + self.plan = [] + objects = tuple(int(x) for x in os.environ.get("ATEC_PCA_OBJECTS", "3,2,1").replace(" ", ",").split(",") if x) + self.objects = objects + for obj_idx in objects: + c, grasp_rot = self._estimate_grasp(rgb, depth, obj_idx) + if obj_idx == 1: + grasp_rot = _quat_wxyz_to_rot(np.array([0.0, 0.709, 0.705, 0.0], dtype=np.float64)) + # The submit-style RGB-D PCA estimate is biased toward the visible + # left crescent of the banana. Keep GraspGen/PCA for its centre, + # but use the task-calibrated top-down wrist pose that the runner + # already validated for object_3. + if obj_idx == 3 and os.environ.get("ATEC_PCA_OBJ3_USE_PCA_ROT") != "1": + grasp_rot = _quat_wxyz_to_rot(np.array([0.0, 1.0, 0.004, 0.0], dtype=np.float64)) + c[:2] += OBJ_CENTER_COMPLETION_OFFSETS[obj_idx] + self._detected_centers[obj_idx] = c.copy() + pick_xy = c[:2] + OBJ_GRASP_CENTER_OFFSETS[obj_idx] + yaw = float(np.arctan2(grasp_rot[1, 1], grasp_rot[0, 1])) + print( + f"[PCA_PLAN] obj={obj_idx} center=({c[0]:.3f},{c[1]:.3f},{c[2]:.3f}) " + f"pick=({pick_xy[0]:.3f},{pick_xy[1]:.3f}) jaw_yaw={yaw:+.2f}", + flush=True, + ) + reach_z = max(float(c[2] + OBJ_TCP_Z[obj_idx]), TABLE_TOP_Z + 0.055) + # The PCA point cloud z is a visible-surface estimate, not the USD + # object root z used by the validated runner. Closing from + # c[2]+offset is too high for object_1 and makes the gripper miss + # the cube. Use the calibrated task close plane instead. + root_z_est = OBJ_ROOT_Z_EST.get(obj_idx, TABLE_TOP_Z + 0.045) + close_z = max(root_z_est + OBJ_CLOSE_Z_OFFSETS.get(obj_idx, 0.020), TABLE_TOP_Z + 0.030) + lift_z = TABLE_TOP_Z + (OBJ3_LIFT_CLEARANCE if obj_idx == 3 else 0.30) + release_z = TABLE_TOP_Z + (OBJ3_CARRY_CLEARANCE if obj_idx == 3 else (0.32 if obj_idx == 1 else 0.24)) + open_z = TABLE_TOP_Z + (OBJ3_CARRY_CLEARANCE if obj_idx == 3 else (0.24 if obj_idx == 1 else 0.15)) + place_xy = np.array([BASKET_CENTER_X, BASKET_CENTER_Y]) + OBJ_PLACE_XY_OFFSETS.get( + obj_idx, np.zeros(2, dtype=np.float64) + ) + # Keep the calibrated top-down task quaternion for all objects. The + # PCA/AABB centre supplies translation; Task-E contact tuning supplies + # the wrist orientation and release heights. + finger_xy = pick_xy.copy() + OBJ_FINGER_XY_OFFSETS.get(obj_idx, np.zeros(2, dtype=np.float64)) if obj_idx in (1, 2, 3) else None + close_finger_xy = ( + pick_xy + + OBJ_PRECLOSE_INSERT_OFFSETS.get(obj_idx, np.zeros(2, dtype=np.float64)) + + OBJ_FINGER_XY_OFFSETS.get(obj_idx, np.zeros(2, dtype=np.float64)) + ) + closed_grip = OBJ3_HOLD_GRIP_DEFAULT.copy() if obj_idx == 3 else GRIP_CLOSE + finger_z = reach_z if obj_idx in (1, 2) else None + place_rot = grasp_rot if obj_idx in (1, 2) else topdown + self._add_pose([pick_xy[0], pick_xy[1], TABLE_TOP_Z + 0.30], grasp_rot, GRIP_OPEN, 90, label=f"obj{obj_idx}_pre") + servo_rel_z = OBJ_FINGER_TARGET_REL_Z.get(obj_idx) + if obj_idx == 3 and OBJ3_ENABLE_INSERT: + # Diagnostic-only guarded side approach. Local tests showed + # low open-finger insertion can shove the banana laterally, so + # the default path below matches the successful GraspNet runner: + # reach the calibrated contact point first, then close there. + side_finger_xy = close_finger_xy + OBJ3_PREGRASP_OFFSET + self._add_pose( + [side_finger_xy[0], side_finger_xy[1], reach_z], + grasp_rot, + GRIP_OPEN, + OBJ3_SIDE_APPROACH_STEPS, + finger_xy=side_finger_xy, + finger_z=OBJ3_APPROACH_FINGER_Z, + servo_obj_z=root_z_est, + servo_target_rel_z=None, + label=f"obj{obj_idx}_side_pre", + ) + self._add_pose( + [side_finger_xy[0], side_finger_xy[1], close_z], + grasp_rot, + GRIP_OPEN, + OBJ3_SIDE_LOW_STEPS, + finger_xy=side_finger_xy, + finger_z=OBJ3_PREGRASP_LOW_FINGER_Z, + servo_obj_z=root_z_est, + servo_target_rel_z=None, + label=f"obj{obj_idx}_side_low", + ) + self._add_pose( + [close_finger_xy[0], close_finger_xy[1], close_z], + grasp_rot, + GRIP_OPEN, + OBJ3_INSERT_STEPS, + finger_xy=close_finger_xy, + finger_z=OBJ3_PREGRASP_LOW_FINGER_Z, + servo_obj_z=root_z_est, + servo_target_rel_z=None, + label=f"obj{obj_idx}_insert", + ) + else: + self._add_pose( + [pick_xy[0], pick_xy[1], reach_z], + grasp_rot, + GRIP_OPEN, + OBJ_REACH_STEPS[obj_idx], + finger_xy=finger_xy, + finger_z=None, + servo_obj_z=root_z_est, + servo_target_rel_z=None, + label=f"obj{obj_idx}_reach", + ) + if obj_idx != 3 and np.linalg.norm(OBJ_PRECLOSE_INSERT_OFFSETS.get(obj_idx, np.zeros(2, dtype=np.float64))) > 1e-6: + self._add_pose( + [close_finger_xy[0], close_finger_xy[1], close_z], + grasp_rot, + GRIP_OPEN, + 180, + finger_xy=close_finger_xy, + finger_z=None, + servo_obj_z=root_z_est, + servo_target_rel_z=servo_rel_z, + label=f"obj{obj_idx}_insert", + ) + obj3_finger_z = OBJ3_CLOSE_FINGER_Z if obj_idx == 3 else None + self._add_pose( + [close_finger_xy[0], close_finger_xy[1], close_z], + grasp_rot, + closed_grip, + OBJ_CLOSE_STEPS[obj_idx], + finger_xy=close_finger_xy, + finger_z=obj3_finger_z, + servo_obj_z=root_z_est, + servo_target_rel_z=None if obj_idx == 3 else servo_rel_z, + label=f"obj{obj_idx}_close", + ) + if obj_idx == 3: + self._add_pose( + [close_finger_xy[0], close_finger_xy[1], close_z], + grasp_rot, + closed_grip, + OBJ3_LOW_HOLD_STEPS, + finger_xy=close_finger_xy, + finger_z=OBJ3_CLOSE_FINGER_Z, + servo_obj_z=root_z_est, + servo_target_rel_z=None, + label=f"obj{obj_idx}_low_hold", + ) + if obj_idx == 1: + self._add_pose( + [close_finger_xy[0], close_finger_xy[1], close_z], + grasp_rot, + GRIP_CLOSE, + 160, + finger_xy=None, + finger_z=None, + freeze_arm=True, + label=f"obj{obj_idx}_squeeze", + ) + self._add_pose( + [close_finger_xy[0], close_finger_xy[1], lift_z], + grasp_rot, + closed_grip, + OBJ_LIFT_STEPS[obj_idx], + finger_xy=close_finger_xy, + finger_z=OBJ3_LIFT_FINGER_Z if obj_idx == 3 else None, + servo_obj_z=None if obj_idx == 3 else root_z_est, + servo_target_rel_z=None if obj_idx == 3 else servo_rel_z, + label=f"obj{obj_idx}_lift", + ) + if obj_idx == 3: + # After a short lift confirms contact, do not keep a high-air + # friction grasp. Banana is contact-sensitive in official + # physics; a low closed-drag/cradle path preserves contact and + # avoids the DLS high-transport singularity seen in videos. + drag_z = OBJ3_FALLBACK_DRAG_Z + drag_start_finger = close_finger_xy.copy() + drag_mid_obj = np.array([BASKET_CENTER_X, 0.5 * (pick_xy[1] + BASKET_CENTER_Y)], dtype=np.float64) + drag_end_obj = np.array([BASKET_CENTER_X, BASKET_CENTER_Y], dtype=np.float64) + drag_mid_finger = drag_mid_obj + OBJ_FINGER_XY_OFFSETS[3] + drag_end_finger = drag_end_obj + OBJ_FINGER_XY_OFFSETS[3] + self._add_pose( + [drag_start_finger[0], drag_start_finger[1], drag_z], + topdown, + closed_grip, + OBJ3_DRAG_START_STEPS, + finger_xy=drag_start_finger, + finger_z=drag_z, + label=f"obj{obj_idx}_drag_start", + ) + self._add_pose( + [drag_mid_finger[0], drag_mid_finger[1], drag_z], + topdown, + closed_grip, + OBJ3_DRAG_MID_STEPS, + finger_xy=drag_mid_finger, + finger_z=drag_z, + label=f"obj{obj_idx}_drag_mid", + ) + self._add_pose( + [drag_end_finger[0], drag_end_finger[1], drag_z], + topdown, + closed_grip, + OBJ3_DRAG_END_STEPS, + finger_xy=drag_end_finger, + finger_z=drag_z, + label=f"obj{obj_idx}_drag_end", + ) + self._add_pose( + [drag_end_finger[0], drag_end_finger[1], drag_z], + topdown, + closed_grip, + OBJ3_DRAG_SETTLE_STEPS, + finger_xy=drag_end_finger, + finger_z=drag_z, + label=f"obj{obj_idx}_drag_settle", + ) + self._add_pose( + [drag_end_finger[0], drag_end_finger[1], drag_z], + topdown, + GRIP_OPEN, + OBJ_OPEN_STEPS[obj_idx], + finger_xy=drag_end_finger, + finger_z=drag_z, + label=f"obj{obj_idx}_drag_open", + ) + self._add_pose([RETRACT_X, RETRACT_Y, TABLE_TOP_Z + 0.40], topdown, GRIP_OPEN, 80, label=f"obj{obj_idx}_retract") + continue + mid = np.array([(close_finger_xy[0] + place_xy[0]) * 0.5, (close_finger_xy[1] + place_xy[1]) * 0.5, release_z]) + if obj_idx == 3: + carry_mid_finger = mid[:2] + OBJ_FINGER_XY_OFFSETS[3] + release_finger = place_xy + OBJ_FINGER_XY_OFFSETS[3] + else: + carry_mid_finger = mid[:2] if obj_idx in (1, 2) else None + release_finger = place_xy if obj_idx in (1, 2) else None + carry_finger_z = OBJ3_LIFT_FINGER_Z if obj_idx == 3 else None + self._add_pose( + mid, + place_rot, + closed_grip, + max(OBJ_TRANSPORT_STEPS[obj_idx] // 2, 1), + finger_xy=carry_mid_finger, + finger_z=carry_finger_z, + label=f"obj{obj_idx}_mid", + ) + if obj_idx == 1: + self._add_pose( + mid, + place_rot, + GRIP_CLOSE, + 140, + freeze_arm=True, + label=f"obj{obj_idx}_mid_squeeze", + ) + self._add_pose( + [place_xy[0], place_xy[1], release_z], + place_rot, + closed_grip, + max(OBJ_TRANSPORT_STEPS[obj_idx] - OBJ_TRANSPORT_STEPS[obj_idx] // 2, 1), + finger_xy=release_finger, + finger_z=carry_finger_z, + label=f"obj{obj_idx}_release", + ) + if obj_idx == 3: + # Match the runner's basket-hold phase: keep the gripper closed + # above the release pose while the object centre is servoed into + # the real basket centre before opening. + self._add_pose( + [place_xy[0], place_xy[1], release_z], + place_rot, + closed_grip, + 420, + finger_xy=release_finger, + finger_z=carry_finger_z, + label=f"obj{obj_idx}_basket_hold", + ) + if obj_idx == 1 and os.environ.get("ATEC_PCA_ENABLE_OBJ1_RESCUE") == "1": + self._add_pose([place_xy[0], place_xy[1], release_z], place_rot, GRIP_CLOSE, 1, label="obj1_relocalize_drag") + settle_xy = np.array([BASKET_CENTER_X, BASKET_CENTER_Y], dtype=np.float64) if obj_idx == 1 else place_xy + settle_finger = release_finger if obj_idx == 3 else (settle_xy if obj_idx in (1, 2) else None) + self._add_pose([settle_xy[0], settle_xy[1], open_z], place_rot, closed_grip, 80 if obj_idx != 3 else 120, finger_xy=settle_finger, label=f"obj{obj_idx}_settle") + self._add_pose([settle_xy[0], settle_xy[1], open_z], place_rot, GRIP_OPEN, OBJ_OPEN_STEPS[obj_idx], label=f"obj{obj_idx}_open") + self._add_pose([RETRACT_X, RETRACT_Y, TABLE_TOP_Z + 0.40], topdown, GRIP_OPEN, 80, label=f"obj{obj_idx}_retract") + self.detected = True + + def _add_pose( + self, + pos, + rot, + grip, + steps, + finger_xy=None, + finger_z=None, + servo_obj_z=None, + servo_target_rel_z=None, + freeze_arm=False, + label="", + ): + if int(steps) <= 0: + return + self.plan.append( + PoseTarget( + np.asarray(pos, dtype=np.float64), + np.asarray(rot, dtype=np.float64), + np.asarray(grip, dtype=np.float64), + int(steps), + None if finger_xy is None else np.asarray(finger_xy, dtype=np.float64), + None if finger_z is None else float(finger_z), + None if servo_obj_z is None else float(servo_obj_z), + None if servo_target_rel_z is None else float(servo_target_rel_z), + bool(freeze_arm), + str(label), + ) + ) + + def predicts(self, obs, current_score): + qpos = self._obs_qpos(obs) + if self.t < 25: + self.t += 1 + return {"action": np.zeros((1, 8), dtype=np.float32).tolist(), "giveup": False} + if self.home_count < 80: + self.home_count += 1 + action = np.clip((HOME_Q - DEFAULT_Q) / ACTION_SCALE, -3.0, 3.0) + return {"action": action.reshape(1, -1).astype(np.float32).tolist(), "giveup": False} + if not self.detected: + if ( + os.environ.get("ATEC_PCA_OBJ1_DIRECT_RESCUE") == "1" + and tuple(int(x) for x in os.environ.get("ATEC_PCA_OBJECTS", "3,2,1").replace(" ", ",").split(",") if x) == (1,) + and self._build_object1_drag_rescue(obs) + ): + self.detected = True + else: + self._build_plan(obs) + if self.plan_idx >= len(self.plan): + if ( + not self.fallback_done + and 3 in self.objects + and os.environ.get("ATEC_PCA_ENABLE_FALLBACK") == "1" + ): + self.fallback_done = True + if self._build_object3_drag_fallback(obs): + target = self.plan[self.plan_idx] + pos_w = target.pos_w.copy() + else: + action = np.clip((HOME_Q - DEFAULT_Q) / ACTION_SCALE, -3.0, 3.0) + return {"action": action.reshape(1, -1).astype(np.float32).tolist(), "giveup": False} + else: + action = np.clip((HOME_Q - DEFAULT_Q) / ACTION_SCALE, -3.0, 3.0) + return {"action": action.reshape(1, -1).astype(np.float32).tolist(), "giveup": False} + else: + target = self.plan[self.plan_idx] + pos_w = target.pos_w.copy() + if target.label == "obj1_relocalize_drag": + if self._build_object1_drag_rescue(obs): + target = self.plan[self.plan_idx] + pos_w = target.pos_w.copy() + else: + self.plan_idx += 1 + return {"action": np.zeros((1, 8), dtype=np.float32).tolist(), "giveup": False} + raw_pos_w = pos_w.copy() + dynamic_finger_xy = None + finger_target_w = None + if target.label in ("obj3_basket_hold", "obj3_settle") and os.environ.get( + "ATEC_PCA_OBJ3_OBJECT_SERVO", "1" + ) != "0": + c_now = self._estimate_object3_current_center(obs) + if c_now is not None: + if self._obj3_carry_offset_xy is None: + finger_now = self.ik.finger_center_world(qpos) + observed_offset = finger_now[:2] - c_now[:2] + # Preserve the actual contact relation reached at lift, + # but bound it so a bad visual frame cannot launch the arm. + observed_offset = np.clip(observed_offset, [-0.055, -0.055], [0.055, 0.055]) + if np.all(np.isfinite(observed_offset)): + self._obj3_carry_offset_xy = observed_offset.astype(np.float64) + carry_offset = ( + self._obj3_carry_offset_xy + if self._obj3_carry_offset_xy is not None + else OBJ_FINGER_XY_OFFSETS[3] + ) + object_target_xy = np.array([BASKET_CENTER_X, BASKET_CENTER_Y], dtype=np.float64) + correction = np.zeros(2, dtype=np.float64) + correction = (object_target_xy - c_now[:2]) * OBJ3_OBJECT_SERVO_GAIN + corr_norm = float(np.linalg.norm(correction)) + max_corr = OBJ3_OBJECT_SERVO_MAX_XY + if corr_norm > max_corr: + correction = correction / max(corr_norm, 1e-6) * max_corr + pos_w[:2] = raw_pos_w[:2] + correction + raw_pos_w = pos_w.copy() + # Keep the same finger-to-object contact relation while + # servoing the object centre into the basket. Pointing the + # finger target at c_now pins the hand near the old table pose + # and fights the basket correction. + dynamic_finger_xy = object_target_xy + carry_offset + if ( + os.environ.get("ATEC_PCA_ENABLE_FALLBACK") == "1" + and + os.environ.get("ATEC_PCA_OBJ3_DYNAMIC_FALLBACK", "1") != "0" + and not self.fallback_done + and target.label in ("obj3_mid", "obj3_release", "obj3_basket_hold") + and c_now[1] > BASKET_CENTER_Y + 0.16 + and c_now[2] < TABLE_TOP_Z + 0.045 + and self.step_in_target > 80 + ): + self.fallback_done = True + print( + f"[PCA_FALLBACK_TRIGGER] object_3 stalled c=({c_now[0]:.3f},{c_now[1]:.3f},{c_now[2]:.3f}) " + f"target={target.label} step={self.step_in_target}", + flush=True, + ) + if self._build_object3_drag_fallback(obs): + target = self.plan[self.plan_idx] + pos_w = target.pos_w.copy() + raw_pos_w = pos_w.copy() + dynamic_finger_xy = None + if os.environ.get("ATEC_PCA_DEBUG_TARGET") and self.step_in_target % 25 == 0: + print( + f"[PCA_OBJ_SERVO] {target.label} c=({c_now[0]:.3f},{c_now[1]:.3f}) " + f"target=({object_target_xy[0]:.3f},{object_target_xy[1]:.3f}) " + f"corr=({correction[0]:+.3f},{correction[1]:+.3f})", + flush=True, + ) + if target.finger_xy is not None: + finger = self.ik.finger_center_world(qpos) + gb_b, _ = self.ik.fk_base(qpos[:6]) + gb_w = BASE_POS_W + R_W_B @ gb_b + finger_from_gb = finger - gb_w + desired_finger_xy = target.finger_xy if dynamic_finger_xy is None else dynamic_finger_xy + finger_target_z = target.finger_z if target.finger_z is not None else finger[2] + finger_target_w = np.array([desired_finger_xy[0], desired_finger_xy[1], finger_target_z], dtype=np.float64) + xy_error = finger[:2] - desired_finger_xy + correction = -xy_error + corr_norm = float(np.linalg.norm(correction)) + max_xy = 0.12 + if target.label.startswith("obj3_") and ( + ("_mid" in target.label) + or ("_release" in target.label) + or ("_basket_hold" in target.label) + or ("_settle" in target.label) + or ("_drag" in target.label) + ): + max_xy = OBJ3_FINGER_SERVO_MAX_XY + elif ("_mid" in target.label) or ("_release" in target.label) or ("_settle" in target.label): + max_xy = 0.32 + if corr_norm > max_xy: + correction = correction / max(corr_norm, 1e-6) * max_xy + pos_w[:2] = raw_pos_w[:2] + correction + if target.finger_z is not None: + pos_w[2] = float(target.finger_z - finger_from_gb[2]) + elif target.servo_obj_z is not None and target.servo_target_rel_z is not None: + rel_z = float(finger[2] - target.servo_obj_z) + z_error = float(target.servo_target_rel_z - rel_z) + obj_for_label = 3 if target.label.startswith("obj3_") else 1 + max_z = OBJ_FINGER_SERVO_MAX_Z.get(obj_for_label, 0.050) + if obj_for_label == 3: + z_correction = float(np.clip(z_error, -max_z, max_z)) + else: + z_correction = min(0.0, max(-max_z, z_error)) + pos_w[2] = float(raw_pos_w[2] + z_correction) + if os.environ.get("ATEC_PCA_DEBUG_TARGET") and self.step_in_target % 25 == 0: + print( + f"[PCA_TARGET] plan={self.plan_idx} step={self.step_in_target} " + f"raw=({raw_pos_w[0]:.3f},{raw_pos_w[1]:.3f},{raw_pos_w[2]:.3f}) " + f"gb=({gb_w[0]:.3f},{gb_w[1]:.3f},{gb_w[2]:.3f}) " + f"finger=({finger[0]:.3f},{finger[1]:.3f},{finger[2]:.3f}) " + f"desired=({desired_finger_xy[0]:.3f},{desired_finger_xy[1]:.3f}) " + f"pos=({pos_w[0]:.3f},{pos_w[1]:.3f},{pos_w[2]:.3f})", + flush=True, + ) + # Use a submit-side equivalent of the runner's CartesianController: + # one DLS update from the current qpos per simulator step. Close/reach + # phases prioritize position because centimetres of z error are enough + # to miss the object, while a small wrist error is tolerable. + position_only = ( + ("_reach" in target.label) + or ("_side_pre" in target.label) + or ("_side_low" in target.label) + or ("_insert" in target.label) + or ("_close" in target.label) + or ("_low_hold" in target.label) + or (target.label.startswith("obj3_") and any(key in target.label for key in ("drag", "mid", "release", "basket_hold", "settle"))) + ) + if target.freeze_arm: + q6 = qpos[:6].copy() + elif ( + finger_target_w is not None + and ( + ( + target.label.startswith("fallback_") + and os.environ.get("ATEC_PCA_FALLBACK_FINGER_IK", "0") != "0" + ) + or ( + target.label.startswith("obj3_") + and os.environ.get("ATEC_PCA_OBJ3_USE_FINGER_IK", "0") == "1" + and any(key in target.label for key in ("mid", "release", "basket_hold", "settle")) + ) + ) + ): + q6 = self.ik.solve_finger(qpos, finger_target_w, target.rot_w) + elif os.environ.get("ATEC_PCA_USE_FULL_IK") == "1": + q6 = self.ik.solve(qpos, pos_w, target.rot_w) + else: + q6 = self.ik.step_dls(qpos, pos_w, target.rot_w, position_only=position_only) + q_target = np.concatenate([q6, target.grip]) + if target.label.startswith("obj1_"): + gap = self.ik.finger_gap(qpos) + if ( + self._obj1_hold_grip is None + and + target.label in ("obj1_close", "obj1_lift", "obj1_mid") + and gap <= OBJ1_HOLD_GAP + and self.step_in_target > 10 + ): + self._obj1_hold_grip = qpos[6:8].copy() + if self._obj1_hold_grip is not None and any( + key in target.label for key in ("close", "squeeze", "lift", "mid", "release", "settle") + ): + q_target[6:8] = self._obj1_hold_grip + if target.label.startswith("obj3_"): + gap = self.ik.finger_gap(qpos) + if ( + self._obj3_hold_grip is None + and target.label == "obj3_lift" + and gap <= OBJ3_HOLD_GAP + and self.step_in_target >= int(os.environ.get("ATEC_PCA_OBJ3_LIFT_LATCH_STEP", "20")) + ): + self._obj3_hold_grip = qpos[6:8].copy() + if self._obj3_hold_grip is not None and any( + key in target.label for key in ("close", "low_hold", "lift", "mid", "release", "basket_hold", "settle", "drag") + ): + q_target[6:8] = self._obj3_hold_grip + # Match IsaacLab CartesianController's per-step clamp; gripper fingers + # still close gradually so they do not shove the object sideways. + gripper_max_delta = 0.010 + if target.label.startswith("obj3_") and self._obj3_hold_grip is None and any( + key in target.label for key in ("close", "low_hold") + ): + gripper_max_delta = OBJ3_GRIPPER_MAX_DELTA + max_delta = np.array( + [0.18, 0.18, 0.18, 0.18, 0.18, 0.18, gripper_max_delta, gripper_max_delta], + dtype=np.float64, + ) + q_target = qpos + np.clip(q_target - qpos, -max_delta, max_delta) + action = np.clip((q_target - DEFAULT_Q) / ACTION_SCALE, -5.0, 5.0) + self.step_in_target += 1 + advance = self.step_in_target >= target.steps + if target.label == "obj1_close" and self._obj1_hold_grip is not None: + advance = True + if ( + target.label == "obj3_close" + and self._obj3_hold_grip is not None + and self.step_in_target >= OBJ3_CLOSE_MIN_STEPS + ): + advance = True + if "_squeeze" in target.label: + gap = self.ik.finger_gap(qpos) + if self._obj1_hold_grip is not None and target.label.startswith("obj1_"): + advance = self.step_in_target >= 20 + elif gap > OBJ1_HOLD_GAP and self.step_in_target < 420: + advance = False + if os.environ.get("ATEC_PCA_DEBUG_TARGET") and self.step_in_target % 25 == 0: + print(f"[PCA_SQUEEZE] step={self.step_in_target} gap={gap:.4f} advance={advance}", flush=True) + if advance: + if os.environ.get("ATEC_PCA_DEBUG_TARGET") and target.label.startswith("obj3_"): + c_dbg = self._estimate_object3_current_center(obs) + f_dbg = self.ik.finger_center_world(qpos) + gap_dbg = self.ik.finger_gap(qpos) + c_msg = "none" + if c_dbg is not None: + c_msg = f"({c_dbg[0]:.3f},{c_dbg[1]:.3f},{c_dbg[2]:.3f})" + print( + f"[PCA_STAGE_END] {target.label} c={c_msg} " + f"finger=({f_dbg[0]:.3f},{f_dbg[1]:.3f},{f_dbg[2]:.3f}) " + f"gap={gap_dbg:.4f} hold=" + f"{None if self._obj3_hold_grip is None else [float(v) for v in self._obj3_hold_grip]}", + flush=True, + ) + self.step_in_target = 0 + self.plan_idx += 1 + return {"action": action.reshape(1, -1).astype(np.float32).tolist(), "giveup": False} + + +RETRACT_X = TABLE_CENTER_X + TABLE_HALF_X - 0.05 +RETRACT_Y = TABLE_CENTER_Y diff --git a/demo/solution_pi05.py b/demo/solution_pi05.py new file mode 100644 index 0000000000000000000000000000000000000000..da2855a23aafe562eeb49a19a37b82c1d12e2a6e --- /dev/null +++ b/demo/solution_pi05.py @@ -0,0 +1,169 @@ +"""ATEC Task E adapter for an OpenPI/pi0.5 websocket policy server. + +This is a local evaluation bridge, not the current submission default. Start +the OpenPI server first, then evaluate this solution against the Isaac task. +""" + +from __future__ import annotations + +from collections import deque +import os +import sys +from pathlib import Path + +import numpy as np +import torch +import torchvision.transforms.functional as TF + + +_OPENPI_REPO = Path(os.environ.get("OPENPI_REPO", "/home/ubuntu/src/openpi-ebench-clean")) +_OPENPI_CLIENT = _OPENPI_REPO / "packages" / "openpi-client" / "src" +if str(_OPENPI_CLIENT) not in sys.path: + sys.path.insert(0, str(_OPENPI_CLIENT)) + +from openpi_client import websocket_client_policy # noqa: E402 + + +class AlgSolution: + """Competition-style solution wrapper backed by a pi0.5 action chunk server.""" + + _QPOS_SLICE = slice(0, 8) + _DEFAULT_PROMPT = "identify all objects, pick them up, and place them into the target basket" + + def __init__(self): + self.device = "cuda" if torch.cuda.is_available() else "cpu" + host = os.environ.get("ATEC_PI05_HOST", "127.0.0.1") + port = int(os.environ.get("ATEC_PI05_PORT", "8000")) + self.policy = websocket_client_policy.WebsocketClientPolicy(host=host, port=port) + self.prompt = os.environ.get("ATEC_PI05_PROMPT", self._DEFAULT_PROMPT) + + self.default_joint_pos = torch.tensor( + [[0.0, 1.2, -1.5, 0.0, 1.2, 0.0, 0.035, -0.035]], + dtype=torch.float32, + device=self.device, + ) + self.teleop_home_joint_pos = torch.tensor( + [[-0.000033, 0.924525, -1.514983, 0.000011, 1.219900, -0.000033, 0.035000, -0.035000]], + dtype=torch.float32, + device=self.device, + ) + self._home_action = torch.clamp( + (self.teleop_home_joint_pos - self.default_joint_pos) / 0.5, + -1.0, + 1.0, + ) + self._startup_zero_steps = int(os.environ.get("ATEC_PI05_STARTUP_ZERO_STEPS", "25")) + self._home_qpos_tolerance = float(os.environ.get("ATEC_PI05_HOME_QPOS_TOLERANCE", "0.10")) + self._home_hold_steps = int(os.environ.get("ATEC_PI05_HOME_HOLD_STEPS", "5")) + self._action_repeat = max(1, int(os.environ.get("ATEC_PI05_ACTION_REPEAT", "5"))) + self._resize_size = (224, 224) + self.reset_episode() + + def reset_episode(self): + self._startup_step = 0 + self._home_stable_steps = 0 + self._home_done = False + self._action_queue: deque[np.ndarray] = deque() + self._held_action: np.ndarray | None = None + self._held_remaining = 0 + + def _compute_home_action(self, proprio: torch.Tensor) -> tuple[torch.Tensor, bool]: + joint_pos_rel = proprio[:, self._QPOS_SLICE] + qpos = joint_pos_rel + self.default_joint_pos + qerr = self.teleop_home_joint_pos - qpos + within_tolerance = torch.all(torch.abs(qerr) <= self._home_qpos_tolerance, dim=1) + self._home_stable_steps = self._home_stable_steps + 1 if bool(torch.all(within_tolerance)) else 0 + home_reached = self._home_stable_steps >= self._home_hold_steps + return self._home_action.repeat(proprio.shape[0], 1), home_reached + + def _rgb_from_obs(self, obs: dict) -> np.ndarray: + rgb = obs["image"]["video_rgb"] + if isinstance(rgb, torch.Tensor): + rgb = rgb[0].detach().cpu() + if rgb.ndim == 3 and rgb.shape[0] in (3, 4): + rgb = rgb[:3].permute(1, 2, 0) + if rgb.ndim == 3 and rgb.shape[-1] == 4: + rgb = rgb[..., :3] + if rgb.dtype != torch.uint8: + rgb = (rgb.float() * 255.0).clamp(0, 255).to(torch.uint8) + if tuple(rgb.shape[:2]) != self._resize_size: + rgb = TF.resize( + rgb.permute(2, 0, 1), + list(self._resize_size), + interpolation=TF.InterpolationMode.BILINEAR, + antialias=True, + ).permute(1, 2, 0) + return rgb.numpy() + + rgb = np.asarray(rgb[0]) + if rgb.shape[-1] == 4: + rgb = rgb[..., :3] + if np.issubdtype(rgb.dtype, np.floating): + rgb = (rgb * 255.0).clip(0, 255).astype(np.uint8) + return rgb.astype(np.uint8, copy=False) + + def _openpi_obs(self, obs: dict, proprio: torch.Tensor) -> dict: + qpos = (proprio[:, self._QPOS_SLICE] + self.default_joint_pos).detach().cpu().numpy()[0] + joints = np.zeros(12, dtype=np.float32) + gripper = np.zeros(4, dtype=np.float32) + joints[:6] = qpos[:6] + gripper[:2] = qpos[6:8] + rgb = self._rgb_from_obs(obs) + return { + "states/joint": joints, + "states/gripper": gripper, + "images/head": rgb, + "images/hand_left": rgb, + "images/hand_right": rgb, + "prompt": self.prompt, + } + + @staticmethod + def _to_env_action(action16: np.ndarray) -> np.ndarray: + action16 = np.asarray(action16, dtype=np.float32) + env_action = np.zeros(8, dtype=np.float32) + env_action[:6] = action16[:6] + env_action[6:8] = action16[12:14] + return env_action + + def _next_pi05_action(self, obs: dict, proprio: torch.Tensor) -> np.ndarray: + if self._held_action is not None and self._held_remaining > 0: + self._held_remaining -= 1 + return self._held_action + + if not self._action_queue: + response = self.policy.infer(self._openpi_obs(obs, proprio)) + actions = np.asarray(response["actions"], dtype=np.float32) + if actions.ndim != 2 or actions.shape[-1] < 16: + raise ValueError(f"Expected OpenPI actions with shape (T, >=16), got {actions.shape}") + for action16 in actions: + self._action_queue.append(self._to_env_action(action16)) + + self._held_action = self._action_queue.popleft() + self._held_remaining = self._action_repeat - 1 + return self._held_action + + def predicts(self, obs, current_score): + if not isinstance(obs, dict) or "proprio" not in obs: + raise ValueError("Expected obs dict with 'proprio' key.") + + proprio = obs["proprio"].to(self.device) + num_envs = proprio.shape[0] + if num_envs != 1: + raise ValueError("solution_pi05 currently supports num_envs=1 for websocket inference.") + + if self._startup_step < self._startup_zero_steps: + self._startup_step += 1 + return {"action": np.zeros((1, 8), dtype=np.float32).tolist(), "giveup": False} + + if not self._home_done: + home_action, home_reached = self._compute_home_action(proprio) + if home_reached: + self._home_done = True + self._action_queue.clear() + self._held_action = None + self._held_remaining = 0 + return {"action": home_action.detach().cpu().numpy().tolist(), "giveup": False} + + action = self._next_pi05_action(obs, proprio) + return {"action": action.reshape(1, -1).tolist(), "giveup": False} diff --git a/demo/solution_pi05_native8.py b/demo/solution_pi05_native8.py new file mode 100644 index 0000000000000000000000000000000000000000..a480627bc282a10b3fa4486964a8992fc9c5126e --- /dev/null +++ b/demo/solution_pi05_native8.py @@ -0,0 +1,181 @@ +"""ATEC Task E pi0.5 native-8D websocket policy bridge.""" + +from __future__ import annotations + +from collections import deque +import os +import sys +from pathlib import Path + +import numpy as np +import torch +import torchvision.transforms.functional as TF + + +_OPENPI_REPO = Path(os.environ.get("OPENPI_REPO", "/home/ubuntu/src/openpi-ebench-clean")) +_OPENPI_CLIENT = _OPENPI_REPO / "packages" / "openpi-client" / "src" +if str(_OPENPI_CLIENT) not in sys.path: + sys.path.insert(0, str(_OPENPI_CLIENT)) + +from openpi_client import websocket_client_policy # noqa: E402 + + +class AlgSolution: + _QPOS_SLICE = slice(0, 8) + _DEFAULT_PROMPT = "identify all objects, pick them up, and place them into the target basket" + + def __init__(self): + self.device = "cuda" if torch.cuda.is_available() else "cpu" + host = os.environ.get("ATEC_PI05_HOST", "127.0.0.1") + port = int(os.environ.get("ATEC_PI05_PORT", "8000")) + self.policy = websocket_client_policy.WebsocketClientPolicy(host=host, port=port) + self.prompt = os.environ.get("ATEC_PI05_PROMPT", self._DEFAULT_PROMPT) + + self.default_joint_pos = torch.tensor( + [[0.0, 1.2, -1.5, 0.0, 1.2, 0.0, 0.035, -0.035]], + dtype=torch.float32, + device=self.device, + ) + self.teleop_home_joint_pos = torch.tensor( + [[-0.000033, 0.924525, -1.514983, 0.000011, 1.219900, -0.000033, 0.035000, -0.035000]], + dtype=torch.float32, + device=self.device, + ) + self._home_action = torch.clamp( + (self.teleop_home_joint_pos - self.default_joint_pos) / 0.5, + -1.0, + 1.0, + ) + self._startup_zero_steps = int(os.environ.get("ATEC_PI05_STARTUP_ZERO_STEPS", "25")) + self._home_qpos_tolerance = float(os.environ.get("ATEC_PI05_HOME_QPOS_TOLERANCE", "0.10")) + self._home_hold_steps = int(os.environ.get("ATEC_PI05_HOME_HOLD_STEPS", "5")) + self._action_repeat = max(1, int(os.environ.get("ATEC_PI05_ACTION_REPEAT", "1"))) + self._action_clip = float(os.environ.get("ATEC_PI05_ACTION_CLIP", "5.0")) + self._chunk_exec_steps = max(1, int(os.environ.get("ATEC_PI05_CHUNK_EXEC_STEPS", "10"))) + self._zero_noise = os.environ.get("ATEC_PI05_ZERO_NOISE", "0").lower() in ("1", "true", "yes") + self._action_horizon = max(1, int(os.environ.get("ATEC_PI05_ACTION_HORIZON", "10"))) + self._model_action_dim = max(8, int(os.environ.get("ATEC_PI05_MODEL_ACTION_DIM", "32"))) + self._debug = os.environ.get("ATEC_PI05_DEBUG", "0").lower() in ("1", "true", "yes") + self._resize_size = (224, 224) + self.reset_episode() + + def reset_episode(self): + self._startup_step = 0 + self._home_stable_steps = 0 + self._home_done = False + self._action_queue: deque[np.ndarray] = deque() + self._held_action: np.ndarray | None = None + self._held_remaining = 0 + self._debug_step = 0 + self._policy_calls = 0 + + def _compute_home_action(self, proprio: torch.Tensor) -> tuple[torch.Tensor, bool]: + qpos = proprio[:, self._QPOS_SLICE] + self.default_joint_pos + qerr = self.teleop_home_joint_pos - qpos + within_tolerance = torch.all(torch.abs(qerr) <= self._home_qpos_tolerance, dim=1) + self._home_stable_steps = self._home_stable_steps + 1 if bool(torch.all(within_tolerance)) else 0 + home_reached = self._home_stable_steps >= self._home_hold_steps + if self._debug and self._debug_step % 50 == 0: + print( + "[PI05_DEBUG] " + f"home step={self._debug_step} max_abs_qerr={torch.max(torch.abs(qerr)).item():.4f} " + f"stable={self._home_stable_steps}/{self._home_hold_steps} " + f"qpos={qpos[0].detach().cpu().numpy()[:8]}", + flush=True, + ) + return self._home_action.repeat(proprio.shape[0], 1), home_reached + + def _rgb_from_obs(self, obs: dict) -> np.ndarray: + rgb = obs["image"]["video_rgb"] + if isinstance(rgb, torch.Tensor): + rgb = rgb[0].detach().cpu() + if rgb.ndim == 3 and rgb.shape[0] in (3, 4): + rgb = rgb[:3].permute(1, 2, 0) + if rgb.ndim == 3 and rgb.shape[-1] == 4: + rgb = rgb[..., :3] + if rgb.dtype != torch.uint8: + rgb = (rgb.float() * 255.0).clamp(0, 255).to(torch.uint8) + if tuple(rgb.shape[:2]) != self._resize_size: + rgb = TF.resize( + rgb.permute(2, 0, 1), + list(self._resize_size), + interpolation=TF.InterpolationMode.BILINEAR, + antialias=True, + ).permute(1, 2, 0) + return rgb.numpy() + + rgb = np.asarray(rgb[0]) + if rgb.shape[-1] == 4: + rgb = rgb[..., :3] + if np.issubdtype(rgb.dtype, np.floating): + rgb = (rgb * 255.0).clip(0, 255).astype(np.uint8) + return rgb.astype(np.uint8, copy=False) + + def _openpi_obs(self, obs: dict, proprio: torch.Tensor) -> dict: + qpos = (proprio[:, self._QPOS_SLICE] + self.default_joint_pos).detach().cpu().numpy()[0] + openpi_obs = { + "state": qpos.astype(np.float32, copy=False), + "image": self._rgb_from_obs(obs), + "prompt": self.prompt, + } + if self._zero_noise: + openpi_obs["noise"] = np.zeros((self._action_horizon, self._model_action_dim), dtype=np.float32) + return openpi_obs + + def _next_pi05_action(self, obs: dict, proprio: torch.Tensor) -> np.ndarray: + if self._held_action is not None and self._held_remaining > 0: + self._held_remaining -= 1 + return self._held_action + + if not self._action_queue: + response = self.policy.infer(self._openpi_obs(obs, proprio)) + actions = np.asarray(response["actions"], dtype=np.float32) + if actions.ndim != 2 or actions.shape[-1] < 8: + raise ValueError(f"Expected OpenPI native8 actions with shape (T, >=8), got {actions.shape}") + self._policy_calls += 1 + if self._debug: + print( + "[PI05_DEBUG] " + f"policy_call={self._policy_calls} actions_shape={actions.shape} " + f"first_action={actions[0, :8]}", + flush=True, + ) + for action8 in actions[: self._chunk_exec_steps]: + self._action_queue.append(np.clip(action8[:8], -self._action_clip, self._action_clip)) + + self._held_action = self._action_queue.popleft() + self._held_remaining = self._action_repeat - 1 + return self._held_action + + def predicts(self, obs, current_score): + if not isinstance(obs, dict) or "proprio" not in obs: + raise ValueError("Expected obs dict with 'proprio' key.") + + proprio = obs["proprio"].to(self.device) + if proprio.shape[0] != 1: + raise ValueError("solution_pi05_native8 supports num_envs=1.") + + if self._startup_step < self._startup_zero_steps: + self._startup_step += 1 + self._debug_step += 1 + if self._debug and self._startup_step in (1, self._startup_zero_steps): + print(f"[PI05_DEBUG] startup step={self._startup_step}/{self._startup_zero_steps}", flush=True) + return {"action": np.zeros((1, 8), dtype=np.float32).tolist(), "giveup": False} + + if not self._home_done: + home_action, home_reached = self._compute_home_action(proprio) + if home_reached: + self._home_done = True + self._action_queue.clear() + self._held_action = None + self._held_remaining = 0 + if self._debug: + print(f"[PI05_DEBUG] home_done at step={self._debug_step}", flush=True) + self._debug_step += 1 + return {"action": home_action.detach().cpu().numpy().tolist(), "giveup": False} + + action = self._next_pi05_action(obs, proprio) + if self._debug and self._debug_step % 50 == 0: + print(f"[PI05_DEBUG] execute step={self._debug_step} action={action[:8]}", flush=True) + self._debug_step += 1 + return {"action": action.reshape(1, -1).tolist(), "giveup": False} diff --git a/demo/solution_rl.py b/demo/solution_rl.py new file mode 100644 index 0000000000000000000000000000000000000000..5ae0534008f6516aedad1f373568239fcff866fa --- /dev/null +++ b/demo/solution_rl.py @@ -0,0 +1,210 @@ +import os +import torch + +class AlgSolution: + + ACTION_SCALE = 0.5 + EE_BODY_NAME_CANDIDATES = ("gripper_base", "piper_gripper_base") + ARM_JOINT_NAME_CANDIDATES = ( + ["joint1", "joint2", "joint3", "joint4", "joint5", "joint6"], + ["arm_joint1", "arm_joint2", "arm_joint3", "arm_joint4", "arm_joint5", "arm_joint6"], + ) + + def __init__(self): + policy_path = os.path.dirname(os.path.abspath(__file__)) + '/policy.pt' + self.device = 'cuda' + + self.policy = torch.jit.load(policy_path, map_location=self.device) + self.policy.eval() + + self.leg_action_dim = 12 + self.arm_action_dim = 8 + + self.leg_joint_indices = list(range(12)) + self.arm_joint_indices = list(range(12, 20)) + + self.train_to_env_action_scale = torch.tensor( + [ + 0.25, 0.5, 0.5, + 0.25, 0.5, 0.5, + 0.25, 0.5, 0.5, + 0.25, 0.5, 0.5, + ], + device=self.device, + dtype=torch.float32, + ).view(1, -1) + + self.env_to_train_action_scale = torch.tensor( + [ + 4.0, 2.0, 2.0, + 4.0, 2.0, 2.0, + 4.0, 2.0, 2.0, + 4.0, 2.0, 2.0, + ], + device=self.device, + dtype=torch.float32, + ).view(1, -1) + + # Fixed zero base velocity command for policy input. + self.fixed_velocity_commands = torch.tensor( + [0.5, 0.0, 0.0], + device=self.device, + dtype=torch.float32, + ).view(1, 3) + + self.arm_default_action = torch.zeros( + (1, self.arm_action_dim), + device=self.device, + dtype=torch.float32, + ) + + + def _resolve_joint_ids(self, candidates: tuple[list[str], ...]) -> list[int]: + last_error = None + for names in candidates: + try: + ids, found_names = self.robot.find_joints(names) + except ValueError as err: + last_error = err + continue + if len(ids) == len(names): + if candidates is self.ARM_JOINT_NAME_CANDIDATES: + self.arm_joint_names = list(found_names) + return list(ids) + raise ValueError( + f"Cannot resolve required joints from candidates: {candidates}. Last error: {last_error}" + ) + + def _resolve_ee_body_name(self) -> str: + last_error = None + for name in self.EE_BODY_NAME_CANDIDATES: + try: + body_ids, _ = self.robot.find_bodies(name) + except ValueError as err: + last_error = err + continue + if len(body_ids) == 1: + return name + raise ValueError( + f"Cannot resolve EE body from candidates: {self.EE_BODY_NAME_CANDIDATES}. Last error: {last_error}" + ) + + def _ensure_cartesian_targets(self): + self.cartesian_ctrl.reset() + + def _compute_arm_overlay_action(self) -> torch.Tensor: + self._ensure_cartesian_targets() + + arm_jpos_des = self.cartesian_ctrl.compute_base( + self.ee_pos_target_b, + self.ee_quat_target_b, + ) + + full_target = self.robot.data.joint_pos.clone() + full_target[:, self.arm_ids] = arm_jpos_des + full_target[:, self.gripper_ids] = self.gripper_open_pos.repeat(full_target.shape[0], 1) + + return (full_target - self.default_joint_pos) / self.ACTION_SCALE + + def _get_velocity_commands(self, proprio: torch.Tensor) -> torch.Tensor: + """Return fixed velocity commands for policy input.""" + num_envs = proprio.shape[0] + + cmd = self.fixed_velocity_commands.to(dtype=proprio.dtype, device=self.device) + if num_envs > 1: + cmd = cmd.repeat(num_envs, 1) + return cmd + + def _extract_policy_obs(self, obs, action_dim) -> torch.Tensor: + proprio = obs["proprio"].to(self.device) + + expected_dim = 3 + 3 + 3 + 3 + action_dim + action_dim + action_dim + + idx = 0 + _base_lin_vel = proprio[:, idx:idx + 3] + idx += 3 + + base_ang_vel = proprio[:, idx:idx + 3] + idx += 3 + + _velocity_commands_env = proprio[:, idx:idx + 3] + idx += 3 + + projected_gravity = proprio[:, idx:idx + 3] + idx += 3 + + joint_pos_all = proprio[:, idx:idx + action_dim] + idx += action_dim + + joint_vel_all = proprio[:, idx:idx + action_dim] + idx += action_dim + + actions_all = proprio[:, idx:idx + action_dim] + + joint_pos_leg = joint_pos_all[:, self.leg_joint_indices] + joint_vel_leg = joint_vel_all[:, self.leg_joint_indices] + actions_env_leg = actions_all[:, self.leg_joint_indices] + + actions_train_leg = actions_env_leg * self.env_to_train_action_scale.to(dtype=proprio.dtype) + velocity_commands = self._get_velocity_commands(proprio) + + policy_obs = torch.cat( + [ + base_ang_vel * 0.25, + projected_gravity, + velocity_commands, + joint_pos_leg, + joint_vel_leg * 0.05, + actions_train_leg, + ], + dim=-1, + ) + + return policy_obs + + def _map_policy_action_to_env_action(self, action_train: torch.Tensor, action_dim: int) -> torch.Tensor: + """Map training-time 12D leg action to current env 20D full-body action.""" + if action_train.shape[-1] != self.leg_action_dim: + raise ValueError( + f"Policy output dim mismatch: got {action_train.shape[-1]}, expected {self.leg_action_dim}" + ) + + num_envs = action_train.shape[0] + leg_action_env = action_train * self.train_to_env_action_scale + + action_env = torch.zeros( + (num_envs, action_dim), + device=self.device, + dtype=torch.float32, + ) + + action_env[:, self.leg_joint_indices] = leg_action_env + action_env[:, self.arm_joint_indices] = self.arm_default_action.repeat(num_envs, 1) + + return action_env + + def predicts(self, obs, current_score): + """Run policy inference and return current-env full-body action.""" + if current_score > 1: + return {'action': [], 'giveup': True} + proprio = obs["proprio"].to(self.device) + action_dim = (int(proprio.shape[-1]) - 12) // 3 + policy_obs = self._extract_policy_obs(obs, action_dim) + + with torch.inference_mode(): + action_train = self.policy(policy_obs) + + if not isinstance(action_train, torch.Tensor): + action_train = torch.as_tensor( + action_train, device=self.device, dtype=torch.float32 + ) + + action_train = action_train.to(device=self.device, dtype=torch.float32) + + if action_train.ndim == 1: + action_train = action_train.unsqueeze(0) + + action_env = self._map_policy_action_to_env_action(action_train, action_dim) + action_env = action_env.cpu().numpy().tolist() + return {'action': action_env, 'giveup': False} + diff --git a/demo/solution_zero.py b/demo/solution_zero.py new file mode 100644 index 0000000000000000000000000000000000000000..44744fa17d469cccae96940e895b0a2a2c19a67c --- /dev/null +++ b/demo/solution_zero.py @@ -0,0 +1,12 @@ +import torch + +class AlgSolution: + + def __init__(self): + pass + + def predicts(self, obs, current_score): + proprio = obs['proprio'] + action_dim = (int(proprio.shape[-1]) - 12) // 3 + action = [0 for _ in range(action_dim)] + return {'action': action, 'giveup': False} diff --git "a/docs/ATEC2026_TaskE_\350\247\204\345\210\231\347\211\251\347\220\206\351\205\215\347\275\256\344\270\216\346\217\220\344\272\244\350\257\264\346\230\216_20260604.md" "b/docs/ATEC2026_TaskE_\350\247\204\345\210\231\347\211\251\347\220\206\351\205\215\347\275\256\344\270\216\346\217\220\344\272\244\350\257\264\346\230\216_20260604.md" new file mode 100644 index 0000000000000000000000000000000000000000..a02f78e9860dd7a1a74ff85ed3adecd4f1dfb02f --- /dev/null +++ "b/docs/ATEC2026_TaskE_\350\247\204\345\210\231\347\211\251\347\220\206\351\205\215\347\275\256\344\270\216\346\217\220\344\272\244\350\257\264\346\230\216_20260604.md" @@ -0,0 +1,273 @@ +# ATEC2026 L0 Task E:规则、物理配置与当前抓取问题说明 + +更新时间:2026-06-04 +工作目录:`/home/ubuntu/Documents/01Proj/13atec/ATEC2026_Simulation_Challenge` + +## 1. 结论先行 + +1. 当前我们调试的确实是 ATEC2026 官方仿真包里的 `ATEC-TaskE-Piper` 桌面抓取任务,不是 L1 足式/轮腿任务,也不是自定义机械臂任务。 +2. 本地物理配置基本来自官方仓库:Isaac Lab v2.3.2、AgileX Piper、三种 YCB 风格物体、桌面、篮筐、固定 RGB-D 观测与 end-effector RGB-D 观测。Piper/物体/地面摩擦和 solver 参数在源码中可查。 +3. “夹住后滑落”不是一个可以简单甩给 Isaac Sim 的单点 bug。更准确地说:官方物理配置对二指夹爪的摩擦夹持比较敏感,而我们当前 GraspGen-style/PCA submit-side primitive 对香蕉这类非凸弯曲物体仍在依赖摩擦保持;一旦 finger-center、闭合高度、夹爪开度、运输高度或速度有偏差,就会出现短暂抬起后滑落。 +4. 不能通过修改比赛评测环境物理参数来提交。提高 solver iteration、摩擦、接触参数可以作为本地诊断,但最终提交必须在官方 judge 环境下靠 `demo/solution.py` 的观测与动作输出成功。 +5. 当前最强可部署基线仍是 `demo/solution.py` 中的 ACT/XSA 方案;`demo/solution_pca.py` 是实验分支,不应覆盖部署,除非三物体多 seed 连续评估明显超过 ACT/XSA。 + +## 2. 已下载/整理的官方资料 + +本次已下载官方 GitHub README 快照: + +- 本地快照:`docs/sources/ATEC2026_Simulation_Challenge_official_readme_20260604.md` +- 官方源链接: +- 官方 raw README: + +2026-06-04 进一步做了官方 fresh clone 对照,临时目录: + +- `/tmp/ATEC2026_Simulation_Challenge_official_check` +- 官方 HEAD:`dbe7c251f680b02f357a6db67430b18d3ba45ea1` +- 最新提交:`dbe7c25 2026-06-04 10:10:16 +0800 Merge pull request #8 from atecup/fix/tron2a_joint_configuration` + +对照结论: + +- 与 Task E 抓取物理强相关的文件,本地与官方最新版 SHA 完全一致: + - `source/atec_rl_lab/atec_rl_lab/assets/robots/piper.py` + - `source/atec_rl_lab/atec_rl_lab/assets/objects/task_b/object.py` + - `source/atec_rl_lab/atec_rl_lab/tasks/task_e/terrain.py` + - `source/atec_rl_lab/atec_rl_lab/tasks/task_e/mdp/rewards.py` + - `source/atec_rl_lab/atec_rl_lab/tasks/task_e/mdp/terminations.py` +- `source/atec_rl_lab/atec_rl_lab/tasks/task_e/env_cfg.py` 只有 action group 字段名差异:官方最新版使用 `joint_leg` / `joint_wheel` / `joint_arm`,本地使用 `joint_pos_leg` / `joint_vel_wheel` / `joint_pos_arm`;Task E 物体、篮筐、相机、随机 Y-band、reward/termination 和 physics material 逻辑一致。 +- `source/atec_rl_lab/atec_rl_lab/tasks/task_base/envs_base_cfg.py` 有两类差异:action group 字段名差异,以及 base reset joint randomization 从官方 `(1.0, 1.0)` 到本地 `(0.5, 1.5)`;Task E Piper 在 `TaskEEnvPiperCfg` 中关闭了相关 reset events,因此这不是香蕉滑落的原因。 +- `demo/server.py` 官方最新版新增 `/get_action_spec` 接口;本地 server 还没有这个接口。这个只影响选手是否能在提交服务里自定义 action mode/scale/clip,不改变官方仿真物理。 +- `demo/Dockerfile` 本地改成 ACT/XSA 提交模板,官方默认仍是 `solution_zero.py` 示例。这是我们自己的提交镜像选择,不是物理环境差异。 + +同日再次核对官方更新与 issue/PR: + +- `git fetch origin` 后,`origin/main` 仍是 `dbe7c251f680b02f357a6db67430b18d3ba45ea1`,没有比 2026-06-04 10:10:16 更新的 commit。 +- GitHub issues/PR 网页搜索未发现公开 issue 提到 Task E / Piper / grasp / physics / friction / banana 滑落问题。 +- `Piper` 搜索命中的是 PR #2:eye-in-hand camera configuration for B2Piper/B2WPiper/G1,不是 Task E 固定 Piper,也不是夹爪滑落。 +- PR #5 是 participant action spec;PR #8 是 Tron2A joint configuration reset bug,和 Task E 抓取物理无关。 +- 已同步唯一低风险兼容修复:在本地 `demo/server.py` 加入官方 `/get_action_spec` endpoint。若 solution 不实现该方法,返回 `{}`,即沿用默认 action 配置。 + +本地 `readme.md` 与官方 raw README 有少量差异:官方新版 README 增加了 `AlgSolution.get_action_spec()` 可选接口说明;本地文件仍可用于当前代码运行,但提交前应留意官方是否启用了该新接口。 + +另外,用户此前提供的赛事说明包含: + +- L0 Task E:桌面随机摆放三种不同类型物体,桌面级机械臂完成识别、抓取、放置到指定区域。 +- 核心流程:识别、规划、抓取、放置。 +- 代码审查:最高分镜像对应代码需要可复现、合规;技术报告需说明实现思路、代码组织结构、执行流程,使用开源模型需提供下载链接,额外训练模型需提供训练代码和数据来源。 +- 预测阶段只能使用上传镜像中的代码和模型,禁止利用测试集挖掘或外部信息。 + +## 3. 官方仓库对 Task E 的关键要求 + +官方 README 明确该仓库提供仿真资产、任务定义和提交脚本,环境基于 Isaac Lab;Task E 在环境矩阵中对应 `ATEC-TaskE-Piper`。参考: + +- `readme.md` / 官方 README:Task E 使用 `ATEC-TaskE-Piper`。 +- `readme.md`:仓库开发/测试版本为 Isaac Lab v2.3.2。 +- `readme.md`:参赛者必须实现 `demo/solution.py`,类名为 `AlgSolution`,核心函数为 `predicts(obs, current_score)`,返回 `{"action": action, "giveup": False}`。 + +本地 Dockerfile 当前提交布局: + +- `demo/Dockerfile` 将 `solution_act.py` 复制为镜像内 `solution.py`,并带上 `policy_act.pt`。 +- 这说明当前默认提交镜像仍是 ACT/XSA 路线,不是 PCA/AnyGrasp 路线。 +- 若以后要切换到 GraspGen-style/PCA,必须先改 Dockerfile 复制目标,并完成多 seed 稳定评估。 + +## 4. Task E 本地评分逻辑 + +源码位置:`source/atec_rl_lab/atec_rl_lab/tasks/task_e/env_cfg.py` 与 `source/atec_rl_lab/atec_rl_lab/tasks/task_e/mdp/rewards.py`。 + +本地 Task E 有两类奖励: + +1. `grasped_objects_once`:物体被末端执行器接近并抬高到桌面上方一定高度,单物体一次性奖励约 3 分。 +2. `objects_in_basket`:物体进入篮筐成功区域,单物体一次性奖励约 3 分。 + +因此三物体理论满分通常对应: + +- 3 个物体各自“被抓起/抬起”一次:约 9 分。 +- 3 个物体最终入篮:约 9 分。 +- 合计约 18 分。 + +篮筐成功区域在源码中定义为: + +- 成功中心:`BASKET_SUCCESS_CENTER = (1.08, -0.30, TABLE_TOP_Z + 0.15)` +- XY 半宽:`half_x = 0.20`,`half_y = 0.11` +- Z 范围:`TABLE_TOP_Z <= object_z <= TABLE_TOP_Z + 0.15` + +这解释了一个重要现象:视频里看起来“抓到过”只能拿到抓取/抬升分;真正冲榜需要三个物体都稳定落在篮筐成功区域内。 + +## 5. 官方/本地物理配置证据 + +### 5.1 Piper 机械臂配置 + +源码:`source/atec_rl_lab/atec_rl_lab/assets/robots/piper.py` + +关键参数: + +- 机器人资产:`robot/piper/piper.usd` +- 关节:`joint1` 到 `joint8`,其中 `joint7/joint8` 是两指夹爪。 +- 接触传感器:`activate_contact_sensors=True` +- 关节隐式执行器:`effort_limit=100.0`、`velocity_limit=100.0`、`stiffness=800.0`、`damping=80.0` +- articulation solver:`solver_position_iteration_count=4`、`solver_velocity_iteration_count=0` + +源码:`source/atec_rl_lab/atec_rl_lab/tasks/task_e/env_cfg.py` + +Task E Piper 初始状态: + +- 机械臂固定在桌子右侧:`pos=(TABLE_CENTER_X + TABLE_HALF_X, TABLE_CENTER_Y, TABLE_TOP_Z)` +- Task E 中 `piper_cfg.spawn.rigid_props.disable_gravity = True` +- 夹爪初始张开:`joint7=0.035`、`joint8=-0.035` + +这里的 solver iteration 偏低,尤其 `velocity_iteration_count=0` 对接触稳定性不算友好。它不是我们抓取代码改出来的,而是仓库里的 Piper 默认配置。 + +### 5.2 三个物体配置 + +源码:`source/atec_rl_lab/atec_rl_lab/assets/objects/task_b/object.py` + +三种物体: + +- `object_1`:`004_sugar_box.usd` +- `object_2`:`006_mustard_bottle.usd` +- `object_3`:`011_banana.usd` + +共同物理参数: + +- `rigid_body_enabled=True` +- `kinematic_enabled=False` +- `linear_damping=2.0` +- `angular_damping=4.0` +- `max_depenetration_velocity=0.5` +- `mass=0.5` +- `contact_offset=0.01` +- `rest_offset=0.0` + +质量统一 0.5kg 对小香蕉/小盒子来说偏重,会放大二指夹爪靠摩擦夹持时的难度。 + +### 5.3 地面/桌面物理材料 + +源码:`source/atec_rl_lab/atec_rl_lab/tasks/task_e/terrain.py` + +Task E terrain 物理材料: + +- `friction_combine_mode="multiply"` +- `restitution_combine_mode="multiply"` +- `static_friction=1.0` +- `dynamic_friction=1.0` +- `restitution=0.0` + +源码:`source/atec_rl_lab/atec_rl_lab/tasks/task_e/env_cfg.py` + +Task E 在 `__post_init__()` 中执行: + +- `self.scene.terrain = TASK_E_TERRAIN_CFG` +- `self.sim.physics_material = self.scene.terrain.physics_material` +- `self.events.physics_material = None` + +这说明 Task E 关闭了默认的 physics material 随机化,使用固定物理材料。对提交而言,这是好事:不是每次都随机摩擦;但对香蕉这种接触几何,固定摩擦也不保证稳抓。 + +### 5.4 物体随机摆放 + +源码:`source/atec_rl_lab/atec_rl_lab/tasks/task_e/env_cfg.py` + +三个物体在桌面不同 Y-band 中随机: + +- `object_1`:`Y in [0.25, 0.29]` +- `object_2`:`Y in [0.14, 0.20]` +- `object_3`:`Y in [0.03, 0.09]` +- `X in [0.90, 1.10]` + +这与我们后续做 RGB-D band mask、按物体区域分割是一致的;但最终提交不能读 object root,只能从观测估计位置。 + +## 6. 为什么香蕉会“夹住又滑落” + +当前最合理判断不是“完全没有抓取模型”,也不是“Isaac Sim 完全坏了”,而是以下几个因素叠加: + +1. 香蕉是弯曲、非凸、局部接触很窄的物体,Piper 二指夹爪如果只夹在局部曲面上,很容易形成滚动/滑动接触。 +2. 当前物体质量统一 0.5kg,香蕉被设置得和盒子一样重,这对 friction-only pinch 很不友好。 +3. Piper solver 参数 `position=4, velocity=0` 对稳定接触不是很强;NVIDIA/Isaac Sim 文档和论坛中也常见“二指夹爪夹物体滑落、需要调接触/solver/摩擦或控制方式”的讨论。 +4. 我们 submit-style PCA 控制器只能用 RGB-D 和 proprio,不读真实 object root;从单视角点云估计出的 grasp center/yaw/闭合高度稍有偏差,就可能出现“看起来夹得很深,但实际 finger contact normal 不足”的情况。 +5. 旧 runner/采集器有时成功,是因为它能更接近官方 scripted primitive:使用更准确的物体状态/动态 servo/真实 finger-center trace。这个能力迁移到 `demo/solution_pca.py` 的 observation-only 控制时会损失。 + +一句话:这不是“夹爪力不够”这么简单,而是接触几何、闭合高度、夹爪开度、运输阶段轨迹和官方 PhysX 接触参数共同作用。 + +## 7. 能不能改物理配置 + +### 可以做的 + +可以做本地诊断: + +- 临时提高 Piper articulation solver iteration,例如 position 从 4 提到 16、velocity 从 0 提到 4。 +- 临时提高物体/夹爪摩擦、检查 contact offset/rest offset。 +- 用这些实验判断“滑落是否主要来自 PhysX 接触求解敏感性”。 + +### 不建议作为提交依赖 + +最终提交不应依赖修改官方评测物理: + +- 代码审查要求最高分镜像在组委会给定环境上可复现。 +- 如果我们靠本地改物理才能稳,线上 judge 不一定会加载这些修改。 +- 合规路线应是:在官方物理配置下,通过更稳的运动 primitive、低位搬运、under-scoop、慢速稳定、篮筐中心上方再释放等方式完成任务。 + +## 8. 当前方案状态 + +### 8.1 ACT/XSA + +当前默认可部署基线仍是 ACT/XSA: + +- Dockerfile 当前复制 `solution_act.py` 为提交 `solution.py`。 +- 历史评估中 XSA final 曾在 seeds 11/12/13 得到过高分,但也出现过非确定性波动。 +- 这是当前最成熟的镜像路线,但还不能说稳定满分。 + +### 8.2 pi0.5 + +pi0.5 已试过 20-demo 和 100-demo 分支,当前效果差: + +- 20-demo 快速分支 seeds 11/12/13 均为 0。 +- 100-demo 分支 seeds 11/12/13 约为 `0/0/6`,均值约 2。 +- 主要问题更像适配层/数据表示不对,而不是 pi0.5 模型本身弱。 + +### 8.3 AnyGrasp + +AnyGrasp SDK 已接入并可推理,但有 license/不可分发限制: + +- 作为本地 candidate generator 很有价值。 +- 但如果最终提交镜像包含不可分发 SDK 或权重,代码审查风险很高。 +- 可借鉴它的 grasp candidate 思路,但最终最好落成可复现、可分发的几何/PCA/GraspNet-style 方法,或在技术报告中完整说明合法来源和许可。 + +### 8.4 GraspGen-style PCA/AABB + +这是用户要求重点冲刺的真正规划抓取路线: + +- `object_1` 在 `demo/solution_pca.py` 中已有 seed11/12/13 单物体成功证据。 +- `object_2` 在 runner 中有单物体成功证据,但 submit-style 还没有完成稳定迁移。 +- `object_3` 当前已能在部分场景短暂强抬,但 mid/transport/release 阶段仍会滑落,尚未达到可提交稳定性。 + +不能宣称 PCA/AABB 已经满分。它是正确方向之一,但还需要把香蕉运输保持问题和 object_2 submit-side 对齐彻底解决。 + +## 9. 推荐的后续技术路线 + +1. 不要再回退到“只训练 ACT/pi0.5”等黑盒路线;继续保留 ACT/XSA 作为提交底线,同时推进 GraspGen-style/PCA 作为冲榜路线。 +2. 对 object_3 做两个分支: + - 本地物理增强诊断:提高 solver iteration 看是否立刻不滑,以确认接触求解敏感性。 + - 官方物理可提交修复:低位转移、under-scoop、缩短高空纯竖直 lift、抓住后沿篮筐方向慢速保持接触移动、篮筐中心高于边缘处稳定后再开爪。 +3. 对 object_2 单独迁移 runner 成功参数,不要套 object_1/object_3 的补偿。 +4. 所有成功证据必须按多 seed 记录:至少 seeds 11/12/13,最好再加 21/22/23。 +5. 最终切换 Dockerfile 前,必须满足: + - 三物体同一 episode 得分稳定接近或等于 18。 + - 有视频证据。 + - 不读取 env root/object state。 + - 不依赖 AnyGrasp SDK 不可分发权重,或已完成合规说明。 + - 技术报告中能解释模型/算法/开源链接/训练或无训练流程。 + +## 10. 参考链接 + +- ATEC2026 Simulation Challenge 官方仓库: +- 官方 README raw 快照源: +- Isaac Lab pip installation 文档: +- Isaac Sim Physics Simulation Fundamentals: +- NVIDIA 论坛,Object Gripping and picking: +- NVIDIA 论坛,Stable grasping in Isaac Sim: + +## 11. 给团队的交接提醒 + +1. 不要把 `demo/solution_pca.py` 直接当最终提交;它是实验控制器。 +2. 不要把 AnyGrasp SDK 直接塞进最终镜像,除非许可证/技术报告/复现检查全部确认无风险。 +3. 不要修改官方物理参数后宣称线上可复现;改物理只能用于定位问题。 +4. 真正要冲榜,必须把“观测估计中心 -> finger-center 控制 -> 闭合 -> 低位运输 -> 篮筐中心上方稳定释放”串成同一条稳定轨迹。 +5. 当前最该解决的是 object_3 香蕉运输阶段滑落,而不是重新换大模型。 diff --git a/example.md b/example.md new file mode 100644 index 0000000000000000000000000000000000000000..f63ec9a17858ade5cfd1cddc4527fcb33b6a63c9 --- /dev/null +++ b/example.md @@ -0,0 +1,95 @@ +## 1. Example Code Guide + +This document provides a minimal end-to-end example for training, evaluating, and submitting a policy. + +## 2. RL for Locomotion + +### 2.1 Train a PPO Policy (Example) + +The baseline workflow references: https://github.com/fan-ziqi/robot_lab + +Run the following command from the repository root: + +```bash +python scripts/rsl_rl/train.py --task ATEC-Isaac-Velocity-Flat-Unitree-B2-v0 --headless --video +``` + +On an **NVIDIA RTX 5090**, this example typically takes around **90 minutes**. + +Actual training time depends on driver/runtime version, CPU performance, and current GPU load. + +### 2.2 Evaluate the Trained Policy + +After training, evaluate with: + +```bash +python scripts/rsl_rl/play.py --task ATEC-Isaac-Velocity-Flat-Unitree-B2-v0 +``` + +This loads the trained checkpoint and runs rollout in the same task setting. + +### 2.3 Test Locally + +The file `demo/solution.py` is the only entrance for locally testing and online submission. +Use the test command: + +```bash +cd ATEC2026_Simulation_Challenge +python scripts/play_atec_task.py --task ATEC-TaskA-B2Piper --enable_cameras +``` + +Notes: + +- `--task` selects the arena and robot. See the Environment Matrix in `readme.md`. +- Use `--debug` to print runtime status and score. + +Pretrained baseline checkpoint: + +- `./atec_robot_model/baseline/unitree_b2_flat/policy.pt` +This checkpoint path can be modified in `demo/solution.py`. + +![baseline demo](./doc/baseline.gif) + +## 3. IL for Manipoulation + +This section follows the core idea of ACT (Action Chunking with Transformers). + +Reference implementation: https://github.com/tonyzhaozh/act + +### 3.1 Collect Demonstrations + +Collect expert trajectories for Task E: + +```bash +python scripts/act/collect_demos_task_e.py --pick_objects 3 --num_demos 100 --headless --enable_cameras --save_images +``` + +Filter out near-zero actions from the collected dataset: + +```bash +python scripts/act/filter_demos.py \ + --input datasets/atec_task_e/trajectory.hdf5 \ + --output datasets/atec_task_e/trajectory_filtered.hdf5 \ + --threshold 0.001 +``` + +### 3.2 Train ACT Policy + +Run ACT baseline training from the `scripts/act` directory: + +```bash +cd scripts/act +bash baseline.sh +``` + +### 3.3 Run the Trained Policy + +Use the test command: + +```bash +python scripts/play_atec_task.py --task ATEC-TaskE-Piper --enable_cameras +``` + +Note: `./atec_robot_model/baseline/act/policy.pt` is the provided baseline checkpoint. You can replace it with your own trained policy path in `demo/solution`. + +![baseline act demo](./doc/baseline_act.gif) diff --git a/readme.md b/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..c7a5647d81c66cb6f361e6cd2dcffd6289942787 --- /dev/null +++ b/readme.md @@ -0,0 +1,238 @@ +## 1. Introduction + +The ATEC 2026 Simulation Challenge provides a standardized suite of robot simulation environments built on IsaacLab, designed to evaluate both locomotion and loco-manipulation capabilities. Participants may select one or multiple legged robot platforms to complete a set of representative tasks, including *Off-road Navigation*, *Tabletop Manipulation*, *Garbage Collection*, and *Obstacle Traversal*. + +This repository includes simulation assets, task definitions, and reference scripts to support development, evaluation, and submission. + +--- + +### 1.2 Robots and Sensors + +- **Robot platforms** + - Humanoid: Unitree G1 (with two-finger gripper) + - Dual-wheel legged + manipulator: Tron1 + AgileX Piper + - Tron2A legged / wheel + manipulator + - Quadruped + manipulator: Unitree B2 + AgileX Piper + - Wheel-legged quadruped + manipulator: Unitree B2W + AgileX Piper + - Manipulator-only: AgileX Piper +- **Sensor suite** (standardized across platforms) + - 1 × LiDAR + - 1 × eye-to-hand RGB-D camera + - 1 × eye-in-hand RGB-D camera *(humanoids use a stereo pair)* + + ## Robot Platforms + + + | Humanoid | Dual-wheel legged + manipulator | Tron2A legged + manipulator | Tron2A wheel + manipulator | Quadruped + manipulator | Wheel-legged quadruped + manipulator | Manipulator | + | :----------------------------------------------------: | :-------------------------------------------------------: | :-----------------------------------------------------------: | :----------------------------------------------------------: | :----------------------------------------------------: | :-----------------------------------------------------: | :-------------------------------------------------------: | + |

|

|

|

|

|

|

| + +> **Note:** Users may modify or optimize assets (e.g., collision geometry simplification) for training purposes. The provided assets serve as reference models for evaluation. + +--- + +### 1.3 Challenge Arenas + +| Arena | Video | Arena | Video | +| --- | --- | --- | --- | +| Task A · Off-road Navigation |

| Task E · Tabletop Manipulation |

| +| Task B · Garbage Collection |

| Task D · Obstacle Traversal |

| + +> **Note:** For each task, participants are free to select any supported robot morphology. + +--- + +### 1.4 Environment Matrix + +The `atec_rl_lab.tasks` module registers all **arena–robot combinations** as Gym-compatible environments, enabling unified interfaces for evaluation and submission. + + +| Arena \ Robot | G1 | Tron1Piper | Tron2ALegged | Tron2AWheel | B2Piper | B2wPiper | Piper | +| ------------- | --------------- | ----------------------- | ------------------------- | ------------------------ | -------------------- | --------------------- | ------------------ | +| Task A | `ATEC-TaskA-G1` | `ATEC-TaskA-Tron1Piper` | `ATEC-TaskA-Tron2ALegged` | `ATEC-TaskA-Tron2AWheel` | `ATEC-TaskA-B2Piper` | `ATEC-TaskA-B2wPiper` | | +| Task B | `ATEC-TaskB-G1` | `ATEC-TaskB-Tron1Piper` | `ATEC-TaskB-Tron2ALegged` | `ATEC-TaskB-Tron2AWheel` | `ATEC-TaskB-B2Piper` | `ATEC-TaskB-B2wPiper` | | +| Task D | `ATEC-TaskD-G1` | `ATEC-TaskD-Tron1Piper` | `ATEC-TaskD-Tron2ALegged` | `ATEC-TaskD-Tron2AWheel` | `ATEC-TaskD-B2Piper` | `ATEC-TaskD-B2wPiper` | | +| Task E | | | | | | | `ATEC-TaskE-Piper` | + +> **Note:** The provided environments are designed for evaluation and submission only and do not support parallelized training. For training, users should implement custom wrappers or leverage external frameworks for efficient learning. + +--- + +## 2. Installation + +This repository is developed and tested with **Isaac Lab v2.3.2**. Earlier versions (e.g., v1.4.1) are not validated and may require modification. + +Follow the official Isaac Lab installation [guide](https://isaac-sim.github.io/IsaacLab/main/source/setup/installation/pip_installation.html). + +### 2.1 Setup + +Clone repository +```bash +git clone https://github.com/atecup/ATEC2026_Simulation_Challenge.git +cd ATEC2026_Simulation_Challenge +``` + +Activate Isaac Lab Environment + +```bash +conda activate isaaclab +``` + +Install ATEC Extension +```bash +cd source/atec_rl_lab +pip install -e . +``` + +After installation, all `ATEC-*` environments will be available in the active Python environment. + +Download Robot Models +```bash +cd ATEC2026_Simulation_Challenge +curl https://static.atecup.com/atec2026/atec_robot_model.zip -o atec_robot_model.zip +unzip atec_robot_model.zip -d atec_robot_model +``` + +--- + +## 3. Running the Environments + +### 3.1 Environment Check + +```bash +cd ATEC2026_Simulation_Challenge +python scripts/list_envs.py +``` + +Successful execution will list all registered environments, confirming correct module loading. + +--- + +### 3.2 Visualization Utilities + +```bash +scripts/view_robots.py – inspect robot models +scripts/view_task_a.py – Task A visualization +scripts/view_task_b.py – Task B visualization +scripts/view_task_d.py – Task D visualization +scripts/view_task_e.py – Task E visualization +``` + +Example: + +``` +python scripts/view_task_a.py --enable_cameras +``` + +--- + +### 3.3 Submission and Evaluation + +Participants can test their solutions using: +```bash +cd ATEC2026_Simulation_Challenge + +python scripts/play_atec_task.py --task ATEC-TaskA-G1 --enable_cameras +``` + +#### Implementation Requirement + +Participants must implement demo/solution.py, and this file name can not be changed. +* Class: AlgSolution +* Function: predicts(obs, current_score), where **obs** is the observation, and **current_score** is the current score +* Return: {"action": action, "giveup": False}, where action is the prediction action represented by List, and **giveup** is the giveup flag. if **giveup** is True, the scoring job will be terminated. + + +### 3.4 Observations and Actions + +#### Tasks A / B / D + +Observations are grouped into: + +- `Proprioception`: base velocity, joint states, previous actions +- `Exteroception`: LiDAR-based height scan +- `Vision`: RGB-D images from head and end-effector cameras + +All observation terms are: + +- noise-injected +- order-preserved +- concatenated per group + +#### Task E (Manipulation-only) + +Observations include: + +- `Proprioception`: joint states (position + velocity) + +- `Vision`: RGB-D images from end-effector and external camera + + + +**Note:** Joint indices follow fixed ordering per robot (critical for policy deployment). + +- b2_piper (20 DoF) +- b2w_piper (24 DoF) +- G1 (33 DoF) +- tron1a_piper (16 DoF) +- piper (8 DoF) + +#### Action Space + +Robot control actions are organized by joint type. + +- Leg joints and manipulator joints are controlled by joint position commands. +- Wheel joints of wheeled robots are controlled by joint velocity commands. + +The action configuration is as follows: + +``` +joint_pos_leg = mdp.JointPositionActionCfg( + asset_name="robot", + joint_names=[""], + scale=0.5, + use_default_offset=True, + clip=None, + preserve_order=True, +) + +joint_vel_wheel = mdp.JointVelocityActionCfg( + asset_name="robot", + joint_names=[""], + scale=5.0, + use_default_offset=True, + clip=None, + preserve_order=True, +) + +joint_pos_arm = mdp.JointPositionActionCfg( + asset_name="robot", + joint_names=[""], + scale=0.5, + use_default_offset=True, + clip=None, + preserve_order=True, +) +``` + +##### Scaling rules + +- Leg position commands are scaled by 0.5 before being applied to the robot. +- Arm position commands are scaled by 0.5 before being applied to the robot. +- Wheel velocity commands are scaled by 5.0 before being applied to the robot. + +Different robots enable different action items according to their structure: + +- Standard legged robots + (humanoid robots, quadruped mobile manipulator robots, manipulator) do not enable wheel velocity control. +- Wheeled legged robots + (Dual-wheel legged mobile manipulator robots, quadruped-wheel legged mobile manipulator robots) + enable wheel velocity control. + +## Contributors +- **[CUHK Legged Robot Lab](https://cuhkleggedrobotlab.github.io/)** +- **[曾兆阳](https://zengzhaoyang.com/)** +- **[ATEC (Advanced Technology Exploration Community)](https://www.atecup.com)** + +## License +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details. \ No newline at end of file diff --git a/scripts/list_envs.py b/scripts/list_envs.py new file mode 100644 index 0000000000000000000000000000000000000000..b1411ca49cea98cae5af6952b9518f24248d6276 --- /dev/null +++ b/scripts/list_envs.py @@ -0,0 +1,112 @@ +#!/usr/bin/env python3 +"""List all Gym environments registered under ``atec_rl_lab.tasks`` without importing Isaac Sim/Kit. + +This script avoids `import atec_rl_lab.tasks` because that may import IsaacLab/Omniverse modules (e.g., `carb`) +in a pure Python environment. Instead, it scans task modules and executes only `gym.register(...)` statements. +""" + +from __future__ import annotations + +import ast +import sys +from pathlib import Path + +import gymnasium as gym +from prettytable import PrettyTable + + +def _project_root() -> Path: + return Path(__file__).resolve().parents[1] + + +def _find_python_files(pkg_dir: Path) -> list[Path]: + return [ + p for p in pkg_dir.rglob("*.py") + if p.name != "__pycache__" + ] + + +def _exec_only_gym_register(py_file: Path) -> bool: + """Parse a python file and execute only top-level `gym.register(...)` calls. + + Returns True if at least one register call was executed. + """ + src = py_file.read_text(encoding="utf-8") + tree = ast.parse(src, filename=str(py_file)) + + register_calls: list[ast.stmt] = [] + for node in tree.body: + + if isinstance(node, (ast.Import, ast.ImportFrom)): + names = [] + if isinstance(node, ast.Import): + names = [n.name for n in node.names] + else: + mod = node.module or "" + names = [mod] + if any("gym" in n for n in names): + register_calls.append(node) + elif isinstance(node, ast.Expr) and isinstance(node.value, ast.Call): + call = node.value + # detect gym.register(...) + if isinstance(call.func, ast.Attribute) and call.func.attr == "register": + if isinstance(call.func.value, ast.Name) and call.func.value.id == "gym": + register_calls.append(node) + + if not register_calls: + return False + + mod = ast.Module(body=register_calls, type_ignores=[]) + code = compile(mod, filename=str(py_file), mode="exec") + + # Execute in a controlled namespace: provide gymnasium as gym + ns: dict = {"gym": gym} + try: + exec(code, ns, ns) + return True + except Exception as e: + print(f"[WARN] Failed executing gym.register in {py_file}: {e}", file=sys.stderr) + return False + + +def discover_tasks_without_import() -> int: + root = _project_root() + pkg_dir = root / "source" / "atec_rl_lab" / "atec_rl_lab" / "tasks" + if not pkg_dir.exists(): + pkg_dir = root / "atec_rl_lab" / "tasks" + + if not pkg_dir.exists(): + raise FileNotFoundError(f"Cannot find tasks package dir under: {root}") + + count = 0 + for py in _find_python_files(pkg_dir): + if py.name in {"env_cfg.py", "scene_cfg.py", "envs_base_cfg.py"}: + continue + if _exec_only_gym_register(py): + count += 1 + return count + + +def main() -> None: + executed_files = discover_tasks_without_import() + + table = PrettyTable(["S. No.", "Task Name", "Entry Point"]) + table.title = f"Available Environments in ATEC RL Lab (scanned {executed_files} files)" + table.align["Task Name"] = "l" + table.align["Entry Point"] = "l" + + index = 0 + for task_spec in gym.registry.values(): + if "ATEC" in task_spec.id and "Isaac" not in task_spec.id: + table.add_row([index + 1, task_spec.id, str(task_spec.entry_point)]) + index += 1 + + print(table) + + +if __name__ == "__main__": + try: + main() + except ModuleNotFoundError as exc: + print(f"Failed to import dependencies while discovering tasks: {exc}") + raise diff --git a/scripts/play_atec_task.py b/scripts/play_atec_task.py new file mode 100644 index 0000000000000000000000000000000000000000..ca6b606e3a0db1b53466ccd5065eb26a8b2337e5 --- /dev/null +++ b/scripts/play_atec_task.py @@ -0,0 +1,168 @@ +# Created by skywoodsz on 2026/02/07. + +import argparse +import os +import time +import json + +from isaaclab.app import AppLauncher + +from demo.solution import AlgSolution +solution = AlgSolution() + +# ----------------------------------------------------------------------------- +# CLI +# ----------------------------------------------------------------------------- +parser = argparse.ArgumentParser(description="Play Atec Tasks (ENV only, no RL).") +parser.add_argument("--video", action="store_true", default=False, help="Record videos during play.") +parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).") +parser.add_argument( + "--disable_fabric", action="store_true", default=False, help="Disable fabric and use USD I/O operations." +) +parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to simulate.") +parser.add_argument("--task", type=str, default=None, help="Name of the task.") +parser.add_argument("--real-time", action="store_true", default=False, help="Run in real-time, if possible.") +parser.add_argument( + "--debug", + action="store_true", + default=False, + help="Enable debug prints for per-step reward/time metrics.", +) + +# Isaac Sim / Kit args +AppLauncher.add_app_launcher_args(parser) + +args_cli = parser.parse_args() + +# If recording video, need cameras enabled in IsaacLab/Kit +if args_cli.video: + args_cli.enable_cameras = True + +# ----------------------------------------------------------------------------- +# Launch Isaac Sim / Kit +# ----------------------------------------------------------------------------- +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +# ----------------------------------------------------------------------------- +# Imports AFTER simulation_app is created (IsaacLab pattern) +# ----------------------------------------------------------------------------- +import gymnasium as gym # noqa: E402 +import torch # noqa: E402 + +from isaaclab.envs import DirectMARLEnv, multi_agent_to_single_agent # noqa: E402 +from isaaclab.utils.dict import print_dict # noqa: E402 + +import atec_rl_lab.tasks # noqa: F401, E402 (register your tasks) +from isaaclab_tasks.utils import parse_env_cfg +from rl_utils import camera_follow + + +def play() -> tuple[float, float]: + if args_cli.task is None: + raise ValueError("Please provide --task, e.g. --task ATEC-TaskA-G1") + + is_task_e = isinstance(args_cli.task, str) and args_cli.task.startswith("ATEC-TaskE") + # ------------------------------------------------------------------------- + # Create env (plain Gym env) + # ------------------------------------------------------------------------- + env_cfg = parse_env_cfg( + args_cli.task, + device=args_cli.device, + num_envs=args_cli.num_envs, + use_fabric=not args_cli.disable_fabric + ) + + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + + # Convert MARL -> single agent if needed (kept from your original script) + if isinstance(env.unwrapped, DirectMARLEnv): + env = multi_agent_to_single_agent(env) + + # ------------------------------------------------------------------------- + # Optional: video wrapper + # ------------------------------------------------------------------------- + if args_cli.video: + # Put videos in ./logs/videos/play by default (edit as you like) + video_kwargs = { + "video_folder": os.path.abspath(os.path.join("logs", "videos", args_cli.task, "play")), + "step_trigger": lambda step: step == 0, + "video_length": args_cli.video_length, + "disable_logger": True, + } + print("[INFO] Recording videos during play.") + print_dict(video_kwargs, nesting=4) + env = gym.wrappers.RecordVideo(env, **video_kwargs) + + + # ------------------------------------------------------------------------- + # Reset + # ------------------------------------------------------------------------- + obs, _ = env.reset() + + dt = env.unwrapped.step_dt if hasattr(env.unwrapped, "step_dt") else None + timestep = 0 + + # ------------------------------------------------------------------------- + # Play loop + # ------------------------------------------------------------------------- + total_episode_reward = 0.0 + total_elapsed_time = 0.0 + while simulation_app.is_running(): + with torch.inference_mode(): + start_time = time.time() + + # ===== Your controller goes here ===== + resp = solution.predicts(obs, total_episode_reward) + giveup = resp["giveup"] + if giveup: + break + actions = resp["action"] + actions = torch.tensor(actions, dtype=torch.float32, device='cuda').view(1, -1) + obs, reward, terminated, truncated, info = env.step(actions) + if not is_task_e: + camera_follow(env) + + sim_dt = info["Step_dt"] + if isinstance(reward, torch.Tensor): + total_episode_reward += reward.mean().item() / sim_dt + else: + total_episode_reward += float(reward) / sim_dt + + if isinstance(info, dict) and "Elapsed_Time" in info: + elapsed = info["Elapsed_Time"] # simulation time from env as primary source + total_elapsed_time = elapsed.item() if hasattr(elapsed, "item") else float(elapsed) + elif dt is not None: + total_elapsed_time += dt # wall clock time as fallback + + if args_cli.debug: + print(f"total_episode_reward:{total_episode_reward: .2f}") + print(f"total_elapsed_time:{total_elapsed_time: .2f}") + + done = (terminated.item() or truncated.item()) + if done: + break + + timestep += 1 + # If recording one video, exit after video_length steps + if args_cli.video and timestep >= args_cli.video_length: + break + + # Real-time pacing + if args_cli.real_time and dt is not None: + sleep_time = dt - (time.time() - start_time) + if sleep_time > 0: + time.sleep(sleep_time) + + env.close() + + return total_episode_reward, total_elapsed_time + + +if __name__ == "__main__": + score, elapsed_time = play() + print(f"score: {score:.2f}, elapsed_time: {elapsed_time:.2f} seconds") + + # Finally, close the simulation app + print("Closing simulation app...") + simulation_app.close() diff --git a/scripts/rl_utils.py b/scripts/rl_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..08aab72d2cd96af523b842f7421a66408afd9a46 --- /dev/null +++ b/scripts/rl_utils.py @@ -0,0 +1,46 @@ +import torch +import isaaclab.utils.math as math_utils + +def camera_follow(env, robot_name: str = "robot", env_index: int = 0, alpha: float = 0.15): + unwrapped = env.unwrapped + + if not hasattr(unwrapped, "viewport_camera_controller"): + return + + try: + robot = unwrapped.scene[robot_name] + except KeyError as e: + raise KeyError( + f"Robot asset '{robot_name}' not found in env.unwrapped.scene." + ) from e + + device = unwrapped.device + + robot_pos = robot.data.root_pos_w[env_index] + robot_quat = robot.data.root_quat_w[env_index] + + camera_offset = torch.tensor([-6.0, 0.0, 0.8], dtype=torch.float32, device=device) + + target_camera_pos = math_utils.transform_points( + camera_offset.unsqueeze(0), + pos=robot_pos.unsqueeze(0), + quat=robot_quat.unsqueeze(0), + ).squeeze(0) + + target_camera_pos[2] = torch.clamp(target_camera_pos[2], min=0.2) + + if not hasattr(camera_follow, "_smooth_pos"): + camera_follow._smooth_pos = {} + + if env_index not in camera_follow._smooth_pos: + camera_follow._smooth_pos[env_index] = target_camera_pos.clone() + + smooth_camera_pos = camera_follow._smooth_pos[env_index] + smooth_camera_pos = (1.0 - alpha) * smooth_camera_pos + alpha * target_camera_pos + camera_follow._smooth_pos[env_index] = smooth_camera_pos + + unwrapped.viewport_camera_controller.set_view_env_index(env_index=env_index) + unwrapped.viewport_camera_controller.update_view_location( + eye=smooth_camera_pos.detach().cpu().numpy(), + lookat=robot_pos.detach().cpu().numpy(), + ) \ No newline at end of file diff --git a/scripts/view_robots.py b/scripts/view_robots.py new file mode 100644 index 0000000000000000000000000000000000000000..fde6a2cf562b7bacb8159a0072ec809435241812 --- /dev/null +++ b/scripts/view_robots.py @@ -0,0 +1,109 @@ +# Created by skywoodsz on 2026/01/28. +import argparse +import itertools +from isaaclab.app import AppLauncher + +# create argparser +parser = argparse.ArgumentParser(description="View ATEC Robots.") +parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to spawn.") +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" +import isaaclab.sim as sim_utils +from isaaclab.assets import AssetBaseCfg +from isaaclab.scene import InteractiveScene, InteractiveSceneCfg +from dataclasses import replace +from atec_rl_lab.assets.robots import ( + UNITREE_B2_CFG, + UNITREE_B2_PIPER_CFG, + UNITREE_B2W_CFG, + UNITREE_B2W_PIPER_CFG, + TRON1A_WHEEL_CFG, + TRON1A_PIPER_CFG, + TRON2A_LEGGED_CFG, + TRON2A_WHEEL_CFG, + PIPER_CFG, + UNITREE_G1_29DOF_DEX1_CFG +) + +class ATECSceneCfg(InteractiveSceneCfg): + ground = AssetBaseCfg( + prim_path="/World/defaultGroundPlane", spawn=sim_utils.GroundPlaneCfg() + ) + + # lights + dome_light = AssetBaseCfg( + prim_path="/World/Light", + spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75)), + ) + + b2 = replace(UNITREE_B2_CFG, prim_path="{ENV_REGEX_NS}/b2") + + b2w = replace(UNITREE_B2W_CFG, prim_path="{ENV_REGEX_NS}/b2w") + b2w.init_state.pos = (b2w.init_state.pos[0], b2w.init_state.pos[1] + 1.0, b2w.init_state.pos[2] + 0.166) + + b2w_piper = replace(UNITREE_B2W_PIPER_CFG, prim_path="{ENV_REGEX_NS}/b2w_piper") + b2w_piper.init_state.pos = (b2w_piper.init_state.pos[0], b2w_piper.init_state.pos[1] + 2.0, b2w_piper.init_state.pos[2] + 0.166) + + b2_piper = replace(UNITREE_B2_PIPER_CFG, prim_path="{ENV_REGEX_NS}/b2_piper") + b2_piper.init_state.pos = (b2_piper.init_state.pos[0], b2_piper.init_state.pos[1] + 3.0, b2_piper.init_state.pos[2] + 0.166) + + tron1a = replace(TRON1A_WHEEL_CFG, prim_path="{ENV_REGEX_NS}/tron1a") + tron1a.init_state.pos = (tron1a.init_state.pos[0], tron1a.init_state.pos[1] + 4.0, tron1a.init_state.pos[2] + 0.166) + + tron1a_piper = replace(TRON1A_PIPER_CFG, prim_path="{ENV_REGEX_NS}/tron1a_piper") + tron1a_piper.init_state.pos = (tron1a_piper.init_state.pos[0], tron1a_piper.init_state.pos[1] + 5.0, tron1a_piper.init_state.pos[2] + 0.166) + + tron2a_legged = replace(TRON2A_LEGGED_CFG, prim_path="{ENV_REGEX_NS}/tron2a_legged") + tron2a_legged.init_state.pos = (tron2a_legged.init_state.pos[0], tron2a_legged.init_state.pos[1] + 6.0, tron2a_legged.init_state.pos[2] + 0.166) + + tron2a_wheel = replace(TRON2A_WHEEL_CFG, prim_path="{ENV_REGEX_NS}/tron2a_wheel") + tron2a_wheel.init_state.pos = (tron2a_wheel.init_state.pos[0], tron2a_wheel.init_state.pos[1] + 7.0, tron2a_wheel.init_state.pos[2] + 0.166) + + piper = replace(PIPER_CFG, prim_path="{ENV_REGEX_NS}/piper") + piper.init_state.pos = (piper.init_state.pos[0], piper.init_state.pos[1] + 8.0, piper.init_state.pos[2]) + + g1 = replace(UNITREE_G1_29DOF_DEX1_CFG, prim_path="{ENV_REGEX_NS}/g1") + g1.init_state.pos = (g1.init_state.pos[0], g1.init_state.pos[1] + 9.0, g1.init_state.pos[2]) + +def main(): + # Initialize the simulation context + sim_cfg = sim_utils.SimulationCfg(dt=0.01, device=args_cli.device) + sim = sim_utils.SimulationContext(sim_cfg) + # Set main camera + sim.set_camera_view([2.0, 0.0, 2.5], [-0.5, 0.0, 0.5]) + + scene_cfg = ATECSceneCfg( + num_envs=args_cli.num_envs, + env_spacing=4.0, + replicate_physics=True + ) + scene = InteractiveScene(scene_cfg) + # Play the simulator + sim.reset() + scene.reset() + + for name, articulation in scene.articulations.items(): + print("-"*100) + print("Robot name:", name) + print("Bodies:", articulation.num_bodies, "->", articulation.body_names) + print("Joints:", articulation.num_joints, "->", articulation.joint_names) + articulation.set_joint_position_target(articulation.data.default_joint_pos) + + for i in itertools.count(): + if not simulation_app.is_running(): + break + scene.write_data_to_sim() + sim.step() + scene.update(sim.get_physics_dt()) + +if __name__ == "__main__": + main() + # close sim app + simulation_app.close() diff --git a/scripts/view_task_a.py b/scripts/view_task_a.py new file mode 100644 index 0000000000000000000000000000000000000000..a83247f8c5f04894f59b065bfa9c49680eb5a7f4 --- /dev/null +++ b/scripts/view_task_a.py @@ -0,0 +1,57 @@ +# Created by skywoodsz on 2026/01/28. +import argparse +import itertools +import torch +from isaaclab.app import AppLauncher + +# create argparser +parser = argparse.ArgumentParser(description="View ATEC Task A.") +parser.add_argument( + "--num_envs", type=int, default=1, help="Number of environments to spawn." +) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" +from isaaclab.envs import ManagerBasedRLEnv + +from atec_rl_lab.tasks.task_a import TaskAEnvB2Cfg + + +def main(): + env_cfg = TaskAEnvB2Cfg() + env_cfg.scene.num_envs = args_cli.num_envs + + env = ManagerBasedRLEnv(env_cfg) + + for name, articulation in env.scene.articulations.items(): + print("-" * 100) + print("Robot name:", name) + print("Bodies:", articulation.num_bodies, "->", articulation.body_names) + print("Joints:", articulation.num_joints, "->", articulation.joint_names) + articulation.set_joint_position_target(articulation.data.default_joint_pos) + + action_space = env.action_space + obs, info = env.reset() + + for i in itertools.count(): + if not simulation_app.is_running(): + break + action = torch.zeros(action_space.shape, device=env.device) + obs, reward, terminated, truncated, info = env.step(action) + done = terminated | truncated + + if done.any(): + env_ids = done.nonzero(as_tuple=False).squeeze(-1) + env.reset(env_ids=env_ids) + + +if __name__ == "__main__": + main() + # close sim app + simulation_app.close() diff --git a/scripts/view_task_b.py b/scripts/view_task_b.py new file mode 100644 index 0000000000000000000000000000000000000000..29157b0a25fcb81cab8bc3fcf49f7d7e2914202c --- /dev/null +++ b/scripts/view_task_b.py @@ -0,0 +1,58 @@ +# Created by skywoodsz on 2026/01/28. +import argparse +import itertools +import torch +from isaaclab.app import AppLauncher + +# create argparser +parser = argparse.ArgumentParser(description="View ATEC Task A.") +parser.add_argument( + "--num_envs", type=int, default=1, help="Number of environments to spawn." +) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" +from isaaclab.envs import ManagerBasedRLEnv + +from atec_rl_lab.tasks.task_b import TaskBEnvB2Cfg + + +def main(): + env_cfg = TaskBEnvB2Cfg() + env_cfg.scene.num_envs = args_cli.num_envs + + env = ManagerBasedRLEnv(env_cfg) + + for name, articulation in env.scene.articulations.items(): + print("-" * 100) + print("Robot name:", name) + print("Bodies:", articulation.num_bodies, "->", articulation.body_names) + print("Joints:", articulation.num_joints, "->", articulation.joint_names) + articulation.set_joint_position_target(articulation.data.default_joint_pos) + + action_space = env.action_space + obs, info = env.reset() + + for i in itertools.count(): + if not simulation_app.is_running(): + break + action = torch.zeros(action_space.shape, device=env.device) + obs, reward, terminated, truncated, info = env.step(action) + done = terminated | truncated + + if done.any(): + env_ids = done.nonzero(as_tuple=False).squeeze(-1) + env.reset(env_ids=env_ids) + + +if __name__ == "__main__": + main() + # close sim app + simulation_app.close() + diff --git a/scripts/view_task_d.py b/scripts/view_task_d.py new file mode 100644 index 0000000000000000000000000000000000000000..9b5cb7db9536bd76bd51034669527feddce53662 --- /dev/null +++ b/scripts/view_task_d.py @@ -0,0 +1,58 @@ +# Created by skywoodsz on 2026/01/28. +import argparse +import itertools +import torch +from isaaclab.app import AppLauncher + +# create argparser +parser = argparse.ArgumentParser(description="View ATEC Task D.") +parser.add_argument( + "--num_envs", type=int, default=1, help="Number of environments to spawn." +) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" + +from isaaclab.envs import ManagerBasedRLEnv + +from atec_rl_lab.tasks.task_d import TaskDEnvB2Cfg + + +def main(): + env_cfg = TaskDEnvB2Cfg() + env_cfg.scene.num_envs = args_cli.num_envs + + env = ManagerBasedRLEnv(env_cfg) + + for name, articulation in env.scene.articulations.items(): + print("-" * 100) + print("Robot name:", name) + print("Bodies:", articulation.num_bodies, "->", articulation.body_names) + print("Joints:", articulation.num_joints, "->", articulation.joint_names) + articulation.set_joint_position_target(articulation.data.default_joint_pos) + + action_space = env.action_space + obs, info = env.reset() + + for i in itertools.count(): + if not simulation_app.is_running(): + break + action = torch.zeros(action_space.shape, device=env.device) + obs, reward, terminated, truncated, info = env.step(action) + done = terminated | truncated + + if done.any(): + env_ids = done.nonzero(as_tuple=False).squeeze(-1) + env.reset(env_ids=env_ids) + + +if __name__ == "__main__": + main() + # close sim app + simulation_app.close() diff --git a/scripts/view_task_e.py b/scripts/view_task_e.py new file mode 100644 index 0000000000000000000000000000000000000000..62b7f17a72ebe61f2b3384a7c008590e98307428 --- /dev/null +++ b/scripts/view_task_e.py @@ -0,0 +1,57 @@ +import argparse +import itertools +import torch +from isaaclab.app import AppLauncher + +# create argparser +parser = argparse.ArgumentParser(description="View ATEC Task E.") +parser.add_argument( + "--num_envs", type=int, default=1, help="Number of environments to spawn." +) +# append AppLauncher cli args +AppLauncher.add_app_launcher_args(parser) +# parse the arguments +args_cli = parser.parse_args() +# launch omniverse app +app_launcher = AppLauncher(args_cli) +simulation_app = app_launcher.app + +"""Rest everything follows.""" +import isaaclab.sim as sim_utils +from isaaclab.envs import ManagerBasedRLEnv +from atec_rl_lab.tasks.task_e.env_cfg import TaskEEnvPiperCfg + + +def main(): + env_cfg = TaskEEnvPiperCfg() + env_cfg.scene.num_envs = args_cli.num_envs + + env = ManagerBasedRLEnv(env_cfg) + + for name, articulation in env.scene.articulations.items(): + print("-" * 100) + print("Robot name:", name) + print("Bodies:", articulation.num_bodies, "->", articulation.body_names) + print("Joints:", articulation.num_joints, "->", articulation.joint_names) + articulation.set_joint_position_target(articulation.data.default_joint_pos) + + action_space = env.action_space + obs, info = env.reset() + + for i in itertools.count(): + if not simulation_app.is_running(): + break + action = torch.zeros(action_space.shape, device=env.device) + obs, reward, terminated, truncated, info = env.step(action) + done = terminated | truncated + + if done.any(): + env_ids = done.nonzero(as_tuple=False).squeeze(-1) + env.reset(env_ids=env_ids) + + +if __name__ == "__main__": + main() + # close sim app + simulation_app.close() + diff --git a/source/__init__.py b/source/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source/atec_rl_lab/__init__.py b/source/atec_rl_lab/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source/atec_rl_lab/atec_rl_lab.egg-info/PKG-INFO b/source/atec_rl_lab/atec_rl_lab.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..d510f2b9385140c6ffdbd757581eb1f213671924 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab.egg-info/PKG-INFO @@ -0,0 +1,15 @@ +Metadata-Version: 2.4 +Name: atec_rl_lab +Version: 0.2.1 +Summary: Reinforcement Learning Lab for ATEC 2026. +Home-page: https://github.com/skywoodsz/ATEC2026_Simulation_Challenge +Author: CUHK LRL +Maintainer: CUHK LRL +License: Apache 2.0 +Classifier: Programming Language :: Python :: 3 +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: POSIX :: Linux +Requires-Python: >=3.10 +Requires-Dist: argcomplete +Dynamic: home-page +Dynamic: requires-python diff --git a/source/atec_rl_lab/atec_rl_lab.egg-info/SOURCES.txt b/source/atec_rl_lab/atec_rl_lab.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..d0afe08be7a64ffe8b54277efe476f130e5c055f --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab.egg-info/SOURCES.txt @@ -0,0 +1,9 @@ +pyproject.toml +setup.py +atec_rl_lab/__init__.py +atec_rl_lab.egg-info/PKG-INFO +atec_rl_lab.egg-info/SOURCES.txt +atec_rl_lab.egg-info/dependency_links.txt +atec_rl_lab.egg-info/not-zip-safe +atec_rl_lab.egg-info/requires.txt +atec_rl_lab.egg-info/top_level.txt \ No newline at end of file diff --git a/source/atec_rl_lab/atec_rl_lab.egg-info/dependency_links.txt b/source/atec_rl_lab/atec_rl_lab.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/source/atec_rl_lab/atec_rl_lab.egg-info/not-zip-safe b/source/atec_rl_lab/atec_rl_lab.egg-info/not-zip-safe new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab.egg-info/not-zip-safe @@ -0,0 +1 @@ + diff --git a/source/atec_rl_lab/atec_rl_lab.egg-info/requires.txt b/source/atec_rl_lab/atec_rl_lab.egg-info/requires.txt new file mode 100644 index 0000000000000000000000000000000000000000..e60624ffee684bd667d113220ae5f9a1ac27eaec --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab.egg-info/requires.txt @@ -0,0 +1 @@ +argcomplete diff --git a/source/atec_rl_lab/atec_rl_lab.egg-info/top_level.txt b/source/atec_rl_lab/atec_rl_lab.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..16250b20b791a06659e8e01916b702c38c8481d2 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab.egg-info/top_level.txt @@ -0,0 +1 @@ +atec_rl_lab diff --git a/source/atec_rl_lab/atec_rl_lab/__init__.py b/source/atec_rl_lab/atec_rl_lab/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/source/atec_rl_lab/atec_rl_lab/assets/__init__.py b/source/atec_rl_lab/atec_rl_lab/assets/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8c3442ada27f968166211e43f441f85891c2b313 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/assets/__init__.py @@ -0,0 +1,6 @@ +# Created by skywoodsz on 2026/01/28. + +import os + +ATEC_ASSETS_MODEL_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../../")) +ATEC_ASSETS_MODEL_DIR = os.path.join(ATEC_ASSETS_MODEL_DIR, "atec_robot_model") \ No newline at end of file diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/__init__.py b/source/atec_rl_lab/atec_rl_lab/tasks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0500dfbf19ef2922f6b5feb874b81d7abb8dad48 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/__init__.py @@ -0,0 +1,4 @@ +from . import task_a # noqa: F401 +from . import task_b +from . import task_d +from . import task_e diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_a/__init__.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_a/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4c8c33811f896044c696f24e8b518ed560536650 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_a/__init__.py @@ -0,0 +1,58 @@ +import gymnasium as gym + +gym.register( + id = "ATEC-TaskA-G1", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskAEnvG1Cfg" + }, +) + +gym.register( + id = "ATEC-TaskA-Tron1Piper", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskAEnvTron1Cfg" + }, +) + +gym.register( + id = "ATEC-TaskA-Tron2ALegged", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskAEnvTron2ALeggedCfg" + }, +) + +gym.register( + id = "ATEC-TaskA-Tron2AWheel", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskAEnvTron2AWheelCfg" + }, +) + +gym.register( + id = "ATEC-TaskA-B2Piper", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskAEnvB2Cfg" + }, +) + +gym.register( + id = "ATEC-TaskA-B2wPiper", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskAEnvB2WCfg" + }, +) + +from .env_cfg import TaskAEnvCfg, TaskAEnvB2Cfg, TaskAEnvTron2ALeggedCfg, TaskAEnvTron2AWheelCfg +__all__ = ['TaskAEnvCfg', 'TaskAEnvB2Cfg', 'TaskAEnvTron2ALeggedCfg', 'TaskAEnvTron2AWheelCfg'] diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_a/env_cfg.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_a/env_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..813dc0f28d8231744eb7462c0523905027e02cdd --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_a/env_cfg.py @@ -0,0 +1,245 @@ +# Created by skywoodsz on 2026/02/06. + +""" +Implementation of Task A environment configuration with different robots. +""" + +from isaaclab.utils import configclass +from isaaclab.managers import RewardTermCfg as RewTerm +from isaaclab.managers import TerminationTermCfg as DoneTerm +from atec_rl_lab.tasks.task_base import TerminationsCfg +from isaaclab.managers import SceneEntityCfg + +from atec_rl_lab.tasks.task_base import BaseEnvCfg +from .terrain import TASK_A_TERRAIN_CFG +import atec_rl_lab.tasks.task_a.mdp as atec_mdp + +@configclass +class TaskATerminationsCfg(TerminationsCfg): + reach_goal_x = DoneTerm( + func=atec_mdp.robot_x_greater_than, + params={ + "asset_cfg": SceneEntityCfg("robot"), + "x_threshold": 145.0, + }, + time_out=False, + ) + +@configclass +class RewardsCfg: + progress_reward = RewTerm( + func=atec_mdp.CrossXMulti, + params={ + "asset_cfg": SceneEntityCfg("robot"), + "x_thresholds": [-115.0, -35.0, 45.0, 125.0, 140.0], + "rewards": [2.0, 4.0, 8.0, 8.0, 4.0], + "debug": False, + "visual_assets": True, + }, + weight=1.0, + ) + + +@configclass +class TaskAEnvCfg(BaseEnvCfg): + """Environment base configuration for Task A.""" + + def __post_init__(self): + super().__post_init__() + + self.scene.terrain = TASK_A_TERRAIN_CFG + self.sim.physics_material = self.scene.terrain.physics_material + self.rewards = RewardsCfg() + self.terminations = TaskATerminationsCfg() + + # Turn off the DR and noise + self.observations.proprio.enable_corruption = False + self.observations.extero.enable_corruption = False + self.observations.image.enable_corruption = False + self.events.physics_material = None + self.events.base_external_force_torque = None + self.events.reset_robot_joints = None + + self.terminations.fall.params["minimum_height"] = -20.0 + + + +@configclass +class TaskAEnvG1Cfg(TaskAEnvCfg): + """Environment configuration for Task A with Unitree g1.""" + def __post_init__(self): + from atec_rl_lab.assets.robots import UNITREE_G1_29DOF_DEX1_CFG + + self.scene.robot = UNITREE_G1_29DOF_DEX1_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=UNITREE_G1_29DOF_DEX1_CFG.init_state.replace( + pos=(-141, 0, 0.8), + ) + ) + super().__post_init__() + + self.terminations.illegal_contact.params["sensor_cfg"].body_names = [ + UNITREE_G1_29DOF_DEX1_CFG.base_link_name, + ".*_hip_(pitch|roll|yaw)_link" + ] + + joint_names = UNITREE_G1_29DOF_DEX1_CFG.joint_names + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + self.actions.joint_pos_leg.joint_names = joint_names + self.actions.joint_vel_wheel = None + self.actions.joint_pos_arm = None + + +@configclass +class TaskAEnvTron1Cfg(TaskAEnvCfg): + def __post_init__(self): + from atec_rl_lab.assets.robots import TRON1A_PIPER_CFG + + self.scene.robot = TRON1A_PIPER_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=TRON1A_PIPER_CFG.init_state.replace( + pos=(-141, 0, 0.8 + 0.166), + ) + ) + super().__post_init__() + + self.terminations.illegal_contact.params["sensor_cfg"].body_names = [ + TRON1A_PIPER_CFG.base_link_name, + "abad_[LR]_Link" + ] + + joint_names = TRON1A_PIPER_CFG.joint_names + leg_joint_names = TRON1A_PIPER_CFG.leg_joint_names + wheel_joint_names = TRON1A_PIPER_CFG.wheel_joint_names + arm_joint_names = TRON1A_PIPER_CFG.arm_joint_names + + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + + self.actions.joint_pos_leg.joint_names = leg_joint_names + self.actions.joint_vel_wheel.joint_names = wheel_joint_names + self.actions.joint_pos_arm.joint_names = arm_joint_names + + +@configclass +class TaskAEnvTron2ALeggedCfg(TaskAEnvCfg): + def __post_init__(self): + from atec_rl_lab.assets.robots import TRON2A_LEGGED_CFG + + self.scene.robot = TRON2A_LEGGED_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=TRON2A_LEGGED_CFG.init_state.replace( + pos=(-141, 0, 0.8 + 0.166), + ) + ) + super().__post_init__() + + self.terminations.illegal_contact.params["sensor_cfg"].body_names = [ + TRON2A_LEGGED_CFG.base_link_name, + "proximal_.*_[LR]_Link", + ] + + joint_names = TRON2A_LEGGED_CFG.joint_names + leg_joint_names = TRON2A_LEGGED_CFG.leg_joint_names + arm_joint_names = TRON2A_LEGGED_CFG.arm_joint_names + + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + + self.actions.joint_pos_leg.joint_names = leg_joint_names + self.actions.joint_vel_wheel = None + self.actions.joint_pos_arm.joint_names = arm_joint_names + + +@configclass +class TaskAEnvTron2AWheelCfg(TaskAEnvCfg): + def __post_init__(self): + from atec_rl_lab.assets.robots import TRON2A_WHEEL_CFG + + self.scene.robot = TRON2A_WHEEL_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=TRON2A_WHEEL_CFG.init_state.replace( + pos=(-141, 0, 0.8 + 0.166), + ) + ) + super().__post_init__() + + self.terminations.illegal_contact.params["sensor_cfg"].body_names = [ + TRON2A_WHEEL_CFG.base_link_name, + "proximal_.*_[LR]_Link", + ] + + joint_names = TRON2A_WHEEL_CFG.joint_names + leg_joint_names = TRON2A_WHEEL_CFG.leg_joint_names + wheel_joint_names = TRON2A_WHEEL_CFG.wheel_joint_names + arm_joint_names = TRON2A_WHEEL_CFG.arm_joint_names + + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + + self.actions.joint_pos_leg.joint_names = leg_joint_names + self.actions.joint_vel_wheel.joint_names = wheel_joint_names + self.actions.joint_pos_arm.joint_names = arm_joint_names + + +@configclass +class TaskAEnvB2Cfg(TaskAEnvCfg): + def __post_init__(self): + from atec_rl_lab.assets.robots import UNITREE_B2_PIPER_CFG + + self.scene.robot = UNITREE_B2_PIPER_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=UNITREE_B2_PIPER_CFG.init_state.replace( + pos=(-141, 0, 0.58), + ) + ) + super().__post_init__() + + self.terminations.illegal_contact.params["sensor_cfg"].body_names = [ + UNITREE_B2_PIPER_CFG.base_link_name, + ".*_hip", + ".*_thigh" + ] + + joint_names = UNITREE_B2_PIPER_CFG.joint_names + leg_joint_names = UNITREE_B2_PIPER_CFG.leg_joint_names + arm_joint_names = UNITREE_B2_PIPER_CFG.arm_joint_names + + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + + self.actions.joint_pos_leg.joint_names = leg_joint_names + self.actions.joint_pos_arm.joint_names = arm_joint_names + self.actions.joint_vel_wheel = None + +@configclass +class TaskAEnvB2WCfg(TaskAEnvCfg): + def __post_init__(self): + from atec_rl_lab.assets.robots import UNITREE_B2W_PIPER_CFG + + self.scene.robot = UNITREE_B2W_PIPER_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=UNITREE_B2W_PIPER_CFG.init_state.replace( + pos=(-141, 0, 0.78), + ) + ) + super().__post_init__() + + self.terminations.illegal_contact.params["sensor_cfg"].body_names = [ + UNITREE_B2W_PIPER_CFG.base_link_name, + ".*_hip", + ".*_thigh" + ] + + joint_names = UNITREE_B2W_PIPER_CFG.joint_names + leg_joint_names = UNITREE_B2W_PIPER_CFG.leg_joint_names + wheel_joint_names = UNITREE_B2W_PIPER_CFG.wheel_joint_names + arm_joint_names = UNITREE_B2W_PIPER_CFG.arm_joint_names + + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + + self.actions.joint_pos_leg.joint_names = leg_joint_names + self.actions.joint_vel_wheel.joint_names = wheel_joint_names + self.actions.joint_pos_arm.joint_names = arm_joint_names diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_a/mdp/__init__.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_a/mdp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6d07dfe31034b140fde4a1840032bab9e6898371 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_a/mdp/__init__.py @@ -0,0 +1,3 @@ + +from .rewards import * +from .terminations import * \ No newline at end of file diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_a/mdp/rewards.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_a/mdp/rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..97bcfea91576bb5d2272c5637d0a6511ff6791e4 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_a/mdp/rewards.py @@ -0,0 +1,305 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Sequence + +import torch +import isaaclab.sim as sim_utils +from isaaclab.managers.manager_base import ManagerTermBase + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + + +class CrossXMulti(ManagerTermBase): + """Give distributed rewards between x-threshold segments based on progress.""" + + def __init__(self, cfg, env): + super().__init__(cfg, env) + + self._initialized = False + + # reward buffers + self._thresholds = None + self._rewards = None + self._segment_starts = None + self._segment_lengths = None + self._prev_cumulative_reward = None + self._max_robot_x = None + self._triggered = None + self._prev_crossed = None + self._asset_name = None + + # visual assets + self._visual_spawned = False + self._visual_prim_paths = [] + self._last_visual_update_step = -1 + + def _init_buffers( + self, + x_thresholds: Sequence[float], + rewards: Sequence[float], + start_x: float, + ): + if len(x_thresholds) != len(rewards): + raise ValueError( + f"x_thresholds and rewards must have the same length, " + f"got {len(x_thresholds)} and {len(rewards)}." + ) + + if len(x_thresholds) == 0: + raise ValueError("x_thresholds cannot be empty.") + + self._thresholds = torch.tensor( + x_thresholds, device=self._env.device, dtype=torch.float32 + ) + self._rewards = torch.tensor( + rewards, device=self._env.device, dtype=torch.float32 + ) + + # Segment i is [segment_starts[i], thresholds[i]] and accumulates rewards[i]. + self._segment_starts = torch.cat( + [ + torch.tensor([start_x], device=self._env.device, dtype=torch.float32), + self._thresholds[:-1], + ] + ) + self._segment_lengths = self._thresholds - self._segment_starts + if torch.any(self._segment_lengths <= 0): + raise ValueError( + "x_thresholds must be strictly increasing and greater than start_x." + ) + + num_checkpoints = len(x_thresholds) + + self._triggered = torch.zeros( + (self._env.num_envs, num_checkpoints), + device=self._env.device, + dtype=torch.bool, + ) + self._prev_crossed = torch.zeros( + (self._env.num_envs, num_checkpoints), + device=self._env.device, + dtype=torch.bool, + ) + self._prev_cumulative_reward = None + self._max_robot_x = None + + self._initialized = True + + def _compute_cumulative_reward(self, robot_x: torch.Tensor) -> torch.Tensor: + # Sum segment-wise linear progress, each segment saturates to its own max reward. + progress = (robot_x.unsqueeze(1) - self._segment_starts.unsqueeze(0)) / self._segment_lengths.unsqueeze(0) + progress = progress.clamp(min=0.0, max=1.0) + return (progress * self._rewards.unsqueeze(0)).sum(dim=1) + + def _set_prim_color(self, prim_path: str, color: tuple[float, float, float]): + """Set display color of a spawned cuboid prim.""" + try: + import omni.usd + from pxr import UsdGeom, Vt + + stage = omni.usd.get_context().get_stage() + prim = stage.GetPrimAtPath(prim_path) + if not prim.IsValid(): + return + + gprim = UsdGeom.Gprim(prim) + gprim.CreateDisplayColorAttr() + gprim.GetDisplayColorAttr().Set(Vt.Vec3fArray([color])) + except Exception as e: + print(f"[CrossXMulti] Failed to set color for {prim_path}: {e}") + + def _spawn_threshold_assets_once( + self, + x_thresholds: Sequence[float], + parent_prim_path: str = "/World/Visuals/CrossXMulti", + line_length_y: float = 4.0, + line_thickness_x: float = 0.02, + line_height_z: float = 0.5, + color_default: tuple[float, float, float] = (1.0, 0.2, 0.2), + ): + """Spawn thin cuboids as visual threshold lines. + """ + if self._visual_spawned: + return + + try: + import omni.usd + stage = omni.usd.get_context().get_stage() + if not stage.GetPrimAtPath(parent_prim_path).IsValid(): + from pxr import UsdGeom + UsdGeom.Xform.Define(stage, parent_prim_path) + except Exception: + pass + + self._visual_prim_paths = [] + + for env_id in range(self._env.num_envs): + env_paths = [] + + for i, x_th in enumerate(x_thresholds): + x_world = float(x_th) + y_world = 0.0 + z_world = 2.0 + line_height_z * 0.5 + + prim_path = f"{parent_prim_path}/env_{env_id}_threshold_{i}" + + cfg = sim_utils.CuboidCfg( + size=(line_thickness_x, line_length_y, line_height_z), + visual_material=None, + collision_props=None, + rigid_props=None, + mass_props=None, + ) + + cfg.func( + prim_path=prim_path, + cfg=cfg, + translation=( + float(x_world), + float(y_world), + float(z_world), + ), + ) + + self._set_prim_color(prim_path, color_default) + env_paths.append(prim_path) + + self._visual_prim_paths.append(env_paths) + + self._visual_spawned = True + + def _update_threshold_asset_colors( + self, + color_default: tuple[float, float, float] = (1.0, 0.2, 0.2), + color_triggered: tuple[float, float, float] = (0.2, 1.0, 0.2), + ): + if not self._visual_spawned: + return + + for env_id in range(self._env.num_envs): + for i in range(len(self._thresholds)): + prim_path = self._visual_prim_paths[env_id][i] + color = color_triggered if self._triggered[env_id, i] else color_default + self._set_prim_color(prim_path, color) + + def reset(self, env_ids=None): + if not self._initialized: + return + + if env_ids is None: + self._triggered.fill_(False) + self._prev_crossed.fill_(False) + if self._asset_name is not None: + robot_x = self._env.scene[self._asset_name].data.root_pos_w[:, 0] + if self._max_robot_x is None: + self._max_robot_x = robot_x.clone() + else: + self._max_robot_x.copy_(robot_x) + cumulative = self._compute_cumulative_reward(self._max_robot_x) + if self._prev_cumulative_reward is None: + self._prev_cumulative_reward = cumulative.clone() + else: + self._prev_cumulative_reward.copy_(cumulative) + elif self._prev_cumulative_reward is not None: + self._prev_cumulative_reward.zero_() + if self._max_robot_x is not None: + self._max_robot_x.zero_() + else: + self._triggered[env_ids] = False + self._prev_crossed[env_ids] = False + if self._asset_name is not None: + robot_x = self._env.scene[self._asset_name].data.root_pos_w[:, 0] + if self._max_robot_x is None: + self._max_robot_x = robot_x.clone() + self._max_robot_x[env_ids] = robot_x[env_ids] + cumulative = self._compute_cumulative_reward(self._max_robot_x) + if self._prev_cumulative_reward is None: + self._prev_cumulative_reward = cumulative.clone() + else: + self._prev_cumulative_reward[env_ids] = cumulative[env_ids] + elif self._prev_cumulative_reward is not None: + self._prev_cumulative_reward[env_ids] = 0.0 + if self._max_robot_x is not None: + self._max_robot_x[env_ids] = 0.0 + + if self._visual_spawned: + self._update_threshold_asset_colors() + + def __call__( + self, + env: ManagerBasedEnv, + asset_cfg, + x_thresholds, + rewards, + start_x: float = -141.0, + debug: bool = False, + visual_assets: bool = False, + visual_update_interval: int = 10, + parent_prim_path: str = "/World/Visuals/CrossXMulti", + line_length_y: float = 20.0, + line_thickness_x: float = 0.02, + line_height_z: float = 0.5, + ) -> torch.Tensor: + # reward buffer init + if not self._initialized: + self._init_buffers(x_thresholds, rewards, start_x=start_x) + + if self._asset_name is None: + self._asset_name = asset_cfg.name + + if visual_assets and not self._visual_spawned: + self._spawn_threshold_assets_once( + x_thresholds=x_thresholds, + parent_prim_path=parent_prim_path, + line_length_y=line_length_y, + line_thickness_x=line_thickness_x, + line_height_z=line_height_z, + ) + + robot = env.scene[asset_cfg.name] + + robot_x = robot.data.root_pos_w[:, 0] # [E] + if self._max_robot_x is None: + self._max_robot_x = robot_x.clone() + prev_max_robot_x = self._max_robot_x.clone() + self._max_robot_x = torch.maximum(self._max_robot_x, robot_x) + max_robot_x = self._max_robot_x + + cumulative_reward = self._compute_cumulative_reward(max_robot_x) + + if self._prev_cumulative_reward is None: + # Avoid giving a spike on the very first frame. + reward = torch.zeros_like(cumulative_reward) + self._prev_cumulative_reward = cumulative_reward.clone() + else: + reward = cumulative_reward - self._prev_cumulative_reward + no_forward_progress = max_robot_x <= (prev_max_robot_x + 1e-6) + reward = torch.where(no_forward_progress, torch.zeros_like(reward), reward) + reward = reward.clamp(min=0.0) + self._prev_cumulative_reward.copy_(cumulative_reward) + + # Safety guard: never return negative reward. + reward = torch.where(reward < 0.0, torch.zeros_like(reward), reward) + + crossed = max_robot_x.unsqueeze(1) > self._thresholds.unsqueeze(0) + newly_crossed = crossed & (~self._prev_crossed) & (~self._triggered) + self._triggered |= newly_crossed + self._prev_crossed = crossed + + if debug: + print( + f"[CrossXMulti] x={robot_x[0].item():.3f}, " + f"max_x={max_robot_x[0].item():.3f}, " + f"cumulative={cumulative_reward[0].item():.3f}, " + f"reward={reward[0].item():.3f}, " + f"newly_crossed={newly_crossed[0].tolist()}" + ) + + if visual_assets and self._visual_spawned: + step = getattr(env, "common_step_counter", 0) + if step != self._last_visual_update_step and step % visual_update_interval == 0: + self._update_threshold_asset_colors() + self._last_visual_update_step = step + + return reward.clamp(min=0.0) diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_a/mdp/terminations.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_a/mdp/terminations.py new file mode 100644 index 0000000000000000000000000000000000000000..f826ed9847577c1a7a6aee2c7636606a9bed1d10 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_a/mdp/terminations.py @@ -0,0 +1,19 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING +import torch + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + + +def robot_x_greater_than( + env: ManagerBasedEnv, + asset_cfg, + x_threshold: float, +) -> torch.Tensor: + """Terminate when robot world x is greater than x_threshold.""" + robot = env.scene[asset_cfg.name] + robot_x = robot.data.root_pos_w[:, 0] # world x + + return robot_x > x_threshold \ No newline at end of file diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_a/terrain.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_a/terrain.py new file mode 100644 index 0000000000000000000000000000000000000000..36efc73c86a210fc0be5e9eabf43c95d1e5704d6 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_a/terrain.py @@ -0,0 +1,88 @@ +# Created by skywoodsz on 2026/02/06. + +from isaaclab.terrains import TerrainImporterCfg, TerrainGeneratorCfg +import isaaclab.terrains as terrain_gen +import isaaclab.sim as sim_utils + +from atec_rl_lab.tasks.task_base import BetterTerrainGenerator, BetterTerrainImporter, BetterTerrainGeneratorCfg +from atec_rl_lab.assets import ATEC_ASSETS_MODEL_DIR + +TASK_A_TERRAIN_CFG = TerrainImporterCfg( + class_type=BetterTerrainImporter, + prim_path="/World/ground", + terrain_type="generator", + terrain_generator=BetterTerrainGeneratorCfg( + class_type=BetterTerrainGenerator, + seed=0, + size=(20.0, 20.0), # for 300m + border_width=0.0, + num_rows=15, + num_cols=1, + horizontal_scale=0.1, + vertical_scale=0.005, + slope_threshold=0.75, + use_cache=False, + terrain_sequence=[ + "flat", # -140 + "flat", # -120 start + "random_rough", # -100 + "random_rough", # -80 + "random_rough", # -60 + "random_rough", # -40 base + "hf_pyramid_slope", # -20 + "hf_pyramid_slope_inv", # 0 + "hf_pyramid_slope", # 20 + "hf_pyramid_slope_inv", # 40 slopes + "pyramid_stairs", # 60 + "pyramid_stairs_inv", # 80 + "pyramid_stairs", # 100 + "pyramid_stairs_inv", # 120 # stairs + "flat", # 140 # goal + ], + sub_terrains={ + "flat": terrain_gen.MeshPlaneTerrainCfg( + proportion=0.1 + ), + "random_rough": terrain_gen.HfRandomUniformTerrainCfg( + proportion=0.1, noise_range=(0.02, 0.10), noise_step=0.02, border_width=0.25 + ), + "hf_pyramid_slope": terrain_gen.HfPyramidSlopedTerrainCfg( + proportion=0.2, slope_range=(0.39, 0.40), platform_width=2.5, border_width=0.25 + ), + "hf_pyramid_slope_inv": terrain_gen.HfInvertedPyramidSlopedTerrainCfg( + proportion=0.2, slope_range=(0.39, 0.40), platform_width=2.5, border_width=0.25 + ), + "pyramid_stairs": terrain_gen.MeshPyramidStairsTerrainCfg( + proportion=0.2, + step_height_range=(0.05, 0.20), + step_width=0.3, + platform_width=3.0, + border_width=1.0, + holes=False, + ), + "pyramid_stairs_inv": terrain_gen.MeshInvertedPyramidStairsTerrainCfg( + proportion=0.2, + step_height_range=(0.05, 0.20), + step_width=0.3, + platform_width=3.0, + border_width=1.0, + holes=False, + ), + }, + ), + max_init_terrain_level=0, + collision_group=-1, + physics_material=sim_utils.RigidBodyMaterialCfg( + friction_combine_mode="multiply", + restitution_combine_mode="multiply", + static_friction=1.0, + dynamic_friction=1.0, + restitution=1.0, + ), + visual_material=sim_utils.MdlFileCfg( + mdl_path=f"{ATEC_ASSETS_MODEL_DIR}/scene/TilesMarbleSpiderWhiteBrickBondHoned.mdl", + project_uvw=True, + texture_scale=(0.25, 0.25), + ), + debug_vis=False, +) diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_b/__init__.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_b/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ed6ca4cd9ca8ba1eb2feb229e1a854fc06e7a972 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_b/__init__.py @@ -0,0 +1,58 @@ +import gymnasium as gym + +gym.register( + id = "ATEC-TaskB-G1", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskBEnvG1Cfg" + }, +) + +gym.register( + id = "ATEC-TaskB-Tron1Piper", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskBEnvTron1Cfg" + }, +) + +gym.register( + id = "ATEC-TaskB-Tron2ALegged", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskBEnvTron2ALeggedCfg" + }, +) + +gym.register( + id = "ATEC-TaskB-Tron2AWheel", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskBEnvTron2AWheelCfg" + }, +) + +gym.register( + id = "ATEC-TaskB-B2Piper", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskBEnvB2Cfg" + }, +) + +gym.register( + id = "ATEC-TaskB-B2wPiper", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskBEnvB2WCfg" + }, +) + +from .env_cfg import TaskBEnvCfg, TaskBEnvB2Cfg, TaskBEnvTron2ALeggedCfg, TaskBEnvTron2AWheelCfg +__all__ = ['TaskBEnvCfg', 'TaskBEnvB2Cfg', 'TaskBEnvTron2ALeggedCfg', 'TaskBEnvTron2AWheelCfg'] diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_b/env_cfg.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_b/env_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..0717a085a5c9fc76dac0c75753c2d22a6805ec2b --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_b/env_cfg.py @@ -0,0 +1,280 @@ +# Created by skywoodsz on 2026/02/09. + +from isaaclab.utils import configclass +from isaaclab.managers import RewardTermCfg as RewTerm +from isaaclab.managers import TerminationTermCfg as DoneTerm +from isaaclab.assets import AssetBaseCfg +import isaaclab.sim as sim_utils + +from .terrain import TASK_B_TERRAIN_CFG +from atec_rl_lab.tasks.task_base import BaseEnvCfg, BaseSceneCfg +from atec_rl_lab.tasks.task_base.envs_base_cfg import TerminationsCfg as BaseTerminationsCfg +from atec_rl_lab.assets.objects import Sugar_cfg, Mustard_cfg, Banana_cfg, Cracker_cfg +from atec_rl_lab.tasks.task_b.mdp.terminations import ObjectsInCircleDone +import atec_rl_lab.tasks.task_b.mdp as atec_mdp + +TARGET_CENTER = (-3.0, -10.0) +TARGET_MARKER_Z = 0.06 + +@configclass +class RewardsCfg: + """Reward terms for the MDP.""" + objects_in_circle = RewTerm( + func=atec_mdp.ObjectsInCircle, + params={"center": TARGET_CENTER, + "radius": 1.0, + "reward_per_object": 1.0}, + weight=1.0, + ) + grasped_objects = RewTerm( + func=atec_mdp.GraspedObjectsByEE, + params={ + "ee_body_name": "gripper_base", + "grasp_dist_thresh": 0.20, + "reward_per_object": 1.0, + }, + weight=1.0, + ) + + +@configclass +class TaskBTerminationsCfg(BaseTerminationsCfg): + objects_in_circle_done = DoneTerm( + func=ObjectsInCircleDone, + params={"center": TARGET_CENTER, "radius": 1.0}, + time_out=False, + ) + + +@configclass +class TaskBEnvCfg(BaseEnvCfg): + """Environment base configuration for Task C.""" + scene: BaseSceneCfg = BaseSceneCfg(num_envs=4096, env_spacing=2.5) + + def __post_init__(self): + super().__post_init__() + + self.scene.terrain = TASK_B_TERRAIN_CFG + self.sim.physics_material = self.scene.terrain.physics_material + self.rewards = RewardsCfg() + self.terminations = TaskBTerminationsCfg() + + # Turn off the DR and noise + self.observations.proprio.enable_corruption = False + self.observations.extero.enable_corruption = False + self.observations.image.enable_corruption = False + self.events.physics_material = None + self.events.base_external_force_torque = None + self.events.reset_robot_joints = None + + import numpy as np + rng = np.random.default_rng(seed=self.seed) + + SUGAR_QUAT = [0.0, 0.707, 0.0, 0.707] + OTHER_QUAT = [0.0, 0.0, -0.707, 0.707] + + for i in range(18): + x = rng.uniform(-15.0, -5.0) + y = rng.uniform(-15.0, -5.0) + + if abs(x) < 1.0 and abs(y) < 1.0: + x += 2.0 + + name = f"Object{i+1}" + + if i < 6: + cfg = Sugar_cfg([x, y, 0.15], SUGAR_QUAT, name) + elif i < 12: + cfg = Mustard_cfg([x, y, 0.10], OTHER_QUAT, name) + else: + cfg = Banana_cfg([x, y, 0.10], OTHER_QUAT, name) + + setattr(self.scene, f"object_{i+1}", cfg) + + +@configclass +class TaskBEnvG1Cfg(TaskBEnvCfg): + """Environment configuration for Task C with Unitree g1.""" + + def __post_init__(self): + from atec_rl_lab.assets.robots import UNITREE_G1_29DOF_DEX1_CFG + self.scene.robot = UNITREE_G1_29DOF_DEX1_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=UNITREE_G1_29DOF_DEX1_CFG.init_state.replace( + pos=(-10, -10, 0.9), + ) + ) + super().__post_init__() + + self.rewards.grasped_objects.params["ee_body_name"] = ( + "left_hand_base_link", + "right_hand_base_link", + ) + self.terminations.illegal_contact.params["sensor_cfg"].body_names = [ + UNITREE_G1_29DOF_DEX1_CFG.base_link_name, + ".*_hip_(pitch|roll|yaw)_link" + ] + + joint_names = UNITREE_G1_29DOF_DEX1_CFG.joint_names + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + self.actions.joint_pos_leg.joint_names = joint_names + self.actions.joint_vel_wheel = None + self.actions.joint_pos_arm = None + + +@configclass +class TaskBEnvTron1Cfg(TaskBEnvCfg): + def __post_init__(self): + from atec_rl_lab.assets.robots import TRON1A_PIPER_CFG + + self.scene.robot = TRON1A_PIPER_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=TRON1A_PIPER_CFG.init_state.replace( + pos=(-10, -10, 0.9 + 0.166), + ) + ) + super().__post_init__() + + self.terminations.illegal_contact.params["sensor_cfg"].body_names = [ + TRON1A_PIPER_CFG.base_link_name, + "abad_[LR]_Link", + ] + + joint_names = TRON1A_PIPER_CFG.joint_names + leg_joint_names = TRON1A_PIPER_CFG.leg_joint_names + wheel_joint_names = TRON1A_PIPER_CFG.wheel_joint_names + arm_joint_names = TRON1A_PIPER_CFG.arm_joint_names + + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + + self.actions.joint_pos_leg.joint_names = leg_joint_names + self.actions.joint_vel_wheel.joint_names = wheel_joint_names + self.actions.joint_pos_arm.joint_names = arm_joint_names + + +@configclass +class TaskBEnvTron2ALeggedCfg(TaskBEnvCfg): + def __post_init__(self): + from atec_rl_lab.assets.robots import TRON2A_LEGGED_CFG + + self.scene.robot = TRON2A_LEGGED_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=TRON2A_LEGGED_CFG.init_state.replace( + pos=(-10, -10, 0.9 + 0.166), + ) + ) + super().__post_init__() + + self.rewards.grasped_objects.params["ee_body_name"] = "gripper_base_Link" + self.terminations.illegal_contact.params["sensor_cfg"].body_names = [ + TRON2A_LEGGED_CFG.base_link_name, + "proximal_.*_[LR]_Link", + ] + + joint_names = TRON2A_LEGGED_CFG.joint_names + leg_joint_names = TRON2A_LEGGED_CFG.leg_joint_names + arm_joint_names = TRON2A_LEGGED_CFG.arm_joint_names + + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + + self.actions.joint_pos_leg.joint_names = leg_joint_names + self.actions.joint_vel_wheel = None + self.actions.joint_pos_arm.joint_names = arm_joint_names + + +@configclass +class TaskBEnvTron2AWheelCfg(TaskBEnvCfg): + def __post_init__(self): + from atec_rl_lab.assets.robots import TRON2A_WHEEL_CFG + + self.scene.robot = TRON2A_WHEEL_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=TRON2A_WHEEL_CFG.init_state.replace( + pos=(-10, -10, 0.9 + 0.166), + ) + ) + super().__post_init__() + + self.rewards.grasped_objects.params["ee_body_name"] = "gripper_base_Link" + self.terminations.illegal_contact.params["sensor_cfg"].body_names = [ + TRON2A_WHEEL_CFG.base_link_name, + "proximal_.*_[LR]_Link", + ] + + joint_names = TRON2A_WHEEL_CFG.joint_names + leg_joint_names = TRON2A_WHEEL_CFG.leg_joint_names + wheel_joint_names = TRON2A_WHEEL_CFG.wheel_joint_names + arm_joint_names = TRON2A_WHEEL_CFG.arm_joint_names + + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + + self.actions.joint_pos_leg.joint_names = leg_joint_names + self.actions.joint_vel_wheel.joint_names = wheel_joint_names + self.actions.joint_pos_arm.joint_names = arm_joint_names + + +@configclass +class TaskBEnvB2Cfg(TaskBEnvCfg): + def __post_init__(self): + + from atec_rl_lab.assets.robots import UNITREE_B2_PIPER_CFG + + self.scene.robot = UNITREE_B2_PIPER_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=UNITREE_B2_PIPER_CFG.init_state.replace( + pos=(-10, -10, 0.68), + ) + ) + super().__post_init__() + + self.terminations.illegal_contact.params["sensor_cfg"].body_names = [ + UNITREE_B2_PIPER_CFG.base_link_name, + ".*_hip", + ".*_thigh", + ] + + joint_names = UNITREE_B2_PIPER_CFG.joint_names + leg_joint_names = UNITREE_B2_PIPER_CFG.leg_joint_names + arm_joint_names = UNITREE_B2_PIPER_CFG.arm_joint_names + + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + + self.actions.joint_pos_leg.joint_names = leg_joint_names + self.actions.joint_pos_arm.joint_names = arm_joint_names + self.actions.joint_vel_wheel = None + +@configclass +class TaskBEnvB2WCfg(TaskBEnvCfg): + def __post_init__(self): + from atec_rl_lab.assets.robots import UNITREE_B2W_PIPER_CFG + + self.scene.robot = UNITREE_B2W_PIPER_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=UNITREE_B2W_PIPER_CFG.init_state.replace( + pos=(-10, -10, 0.78), + ) + ) + super().__post_init__() + + self.terminations.illegal_contact.params["sensor_cfg"].body_names = [ + UNITREE_B2W_PIPER_CFG.base_link_name, + ".*_hip", + ".*_thigh", + ] + + joint_names = UNITREE_B2W_PIPER_CFG.joint_names + leg_joint_names = UNITREE_B2W_PIPER_CFG.leg_joint_names + wheel_joint_names = UNITREE_B2W_PIPER_CFG.wheel_joint_names + arm_joint_names = UNITREE_B2W_PIPER_CFG.arm_joint_names + + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + + self.actions.joint_pos_leg.joint_names = leg_joint_names + self.actions.joint_vel_wheel.joint_names = wheel_joint_names + self.actions.joint_pos_arm.joint_names = arm_joint_names diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_b/mdp/__init__.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_b/mdp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..63302ef807566270a8e685a37efba74bd8947f93 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_b/mdp/__init__.py @@ -0,0 +1,2 @@ +from .rewards import * +from .terminations import * diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_b/mdp/rewards.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_b/mdp/rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..7fe19e8d08ad4bd437326f552fed7115dd588f10 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_b/mdp/rewards.py @@ -0,0 +1,143 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +from isaaclab.managers import RewardTermCfg +from isaaclab.managers.manager_base import ManagerTermBase + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + + +class ObjectsInCircle(ManagerTermBase): + """Count Sugar/Mustard/Banana objects that enter a target circle for the first time. + + The reward is one-time per object per episode: + once an object has been counted, it will not be rewarded again until reset. + """ + + def __init__(self, cfg: RewardTermCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + self._num_objects = 18 + self._counted = torch.zeros( + (self._env.num_envs, self._num_objects), + device=self._env.device, + dtype=torch.bool, + ) + + def reset(self, env_ids=None): + if env_ids is None: + self._counted.fill_(False) + else: + self._counted[env_ids] = False + + def __call__( + self, + env: ManagerBasedEnv, + center: tuple[float, float] = (-3.0, -10.0), + radius: float = 1.0, + reward_per_object: float = 10.0, + z_min: float = 0.0, + z_max: float = 0.5, + ) -> torch.Tensor: + center_xy = torch.tensor(center, device=env.device, dtype=torch.float32) + radius_sq = radius * radius + + inside_flags: list[torch.Tensor] = [] + for obj_idx in range(1, self._num_objects + 1): + obj = env.scene[f"object_{obj_idx}"] + obj_pos = obj.data.root_pos_w[:, :3] + dist_sq = torch.sum((obj_pos[:, :2] - center_xy) ** 2, dim=1) + inside_xy = dist_sq <= radius_sq + inside_z = (obj_pos[:, 2] >= float(z_min)) & (obj_pos[:, 2] <= float(z_max)) + inside_flags.append(inside_xy & inside_z) + + inside = torch.stack(inside_flags, dim=1) + newly_inside = inside & (~self._counted) + self._counted |= inside + + return newly_inside.sum(dim=1).to(torch.float32) * float(reward_per_object) + + +class GraspedObjectsByEE(ManagerTermBase): + """Count objects reached by one or two end-effectors for the first time. + + Each object contributes at most +1 per episode by default. + """ + + def __init__(self, cfg: RewardTermCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + self._num_objects = 18 + self._counted = torch.zeros( + (self._env.num_envs, self._num_objects), + device=self._env.device, + dtype=torch.bool, + ) + self._ee_body_idxs: list[int] | None = None + self._ee_body_names_key: tuple[str, ...] | None = None + + def _normalize_ee_body_names(self, ee_body_name: str | tuple[str, str]) -> tuple[str, ...]: + if isinstance(ee_body_name, str): + return (ee_body_name,) + if isinstance(ee_body_name, tuple): + if len(ee_body_name) not in (1, 2): + raise ValueError("ee_body_name tuple must contain one or two body names.") + return tuple(str(name) for name in ee_body_name) + raise TypeError(f"Unsupported ee_body_name type: {type(ee_body_name)}") + + def _ensure_ee_body_idxs(self, env: ManagerBasedEnv, ee_body_name: str | tuple[str, str]): + names_key = self._normalize_ee_body_names(ee_body_name) + if self._ee_body_idxs is not None and self._ee_body_names_key == names_key: + return + + robot = env.scene["robot"] + body_idxs: list[int] = [] + used_names: list[str] = [] + for name in names_key: + body_ids, found_names = robot.find_bodies(name) + if len(body_ids) == 0: + raise ValueError(f"Cannot find EE body by name regex '{name}'.") + body_idxs.append(int(body_ids[0])) + used_names.append(found_names[0]) + + self._ee_body_idxs = body_idxs + self._ee_body_names_key = names_key + print(f"[GraspedObjectsByEE] using ee bodies: {used_names} (idxs={body_idxs})") + + def reset(self, env_ids=None): + if env_ids is None: + self._counted.fill_(False) + else: + self._counted[env_ids] = False + + def __call__( + self, + env: ManagerBasedEnv, + ee_body_name: str | tuple[str, str] = "gripper_base", + grasp_dist_thresh: float = 0.12, + reward_per_object: float = 1.0, + distance_threshold: float | None = None, + ) -> torch.Tensor: + # Backward compatibility: old cfg used distance_threshold. + if distance_threshold is not None: + grasp_dist_thresh = float(distance_threshold) + + self._ensure_ee_body_idxs(env, ee_body_name) + + robot = env.scene["robot"] + ee_pos = robot.data.body_pos_w[:, self._ee_body_idxs, :3] + threshold_sq = float(grasp_dist_thresh) * float(grasp_dist_thresh) + + reached_flags: list[torch.Tensor] = [] + for obj_idx in range(1, self._num_objects + 1): + obj = env.scene[f"object_{obj_idx}"] + obj_pos = obj.data.root_pos_w[:, :3] + dist_sq = torch.sum((ee_pos - obj_pos.unsqueeze(1)) ** 2, dim=2) + reached_flags.append((dist_sq <= threshold_sq).any(dim=1)) + + reached = torch.stack(reached_flags, dim=1) + newly_reached = reached & (~self._counted) + self._counted |= reached + + return newly_reached.sum(dim=1).to(torch.float32) * float(reward_per_object) diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_b/mdp/terminations.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_b/mdp/terminations.py new file mode 100644 index 0000000000000000000000000000000000000000..650fedd3e8c61f86433662ebb9667db9b6ee1fcd --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_b/mdp/terminations.py @@ -0,0 +1,43 @@ +# Created by skywoodsz on 4/4/26. + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +from isaaclab.managers import TerminationTermCfg +from isaaclab.managers.manager_base import ManagerTermBase + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + + +class ObjectsInCircleDone(ManagerTermBase): + """Terminate when all 18 Task-B objects are inside the target circle.""" + + def __init__(self, cfg: TerminationTermCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + self._num_objects = 18 + + def __call__( + self, + env: ManagerBasedEnv, + center: tuple[float, float] = (-3.0, -10.0), + radius: float = 1.0, + z_min: float = 0.0, + z_max: float = 0.5, + ) -> torch.Tensor: + center_xy = torch.tensor(center, device=env.device, dtype=torch.float32) + radius_sq = float(radius) * float(radius) + + inside_flags: list[torch.Tensor] = [] + for obj_idx in range(1, self._num_objects + 1): + obj = env.scene[f"object_{obj_idx}"] + obj_pos = obj.data.root_pos_w[:, :3] + dist_sq = torch.sum((obj_pos[:, :2] - center_xy) ** 2, dim=1) + inside_xy = dist_sq <= radius_sq + inside_z = (obj_pos[:, 2] >= float(z_min)) & (obj_pos[:, 2] <= float(z_max)) + inside_flags.append(inside_xy & inside_z) + + inside = torch.stack(inside_flags, dim=1) + return inside.all(dim=1) diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_b/terrain.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_b/terrain.py new file mode 100644 index 0000000000000000000000000000000000000000..85d8a9a32d74c71ddf3333f19f696628917ebb1d --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_b/terrain.py @@ -0,0 +1,118 @@ +from __future__ import annotations + +from isaaclab.terrains import ( + SubTerrainBaseCfg, + TerrainGeneratorCfg, + TerrainImporterCfg, +) +import trimesh +import numpy as np +from isaaclab.utils import configclass +import isaaclab.sim as sim_utils +from atec_rl_lab.assets import ATEC_ASSETS_MODEL_DIR + +from atec_rl_lab.tasks.task_base import BetterTerrainGenerator, BetterTerrainImporter + +def flat_terrain_with_trash_bin( + difficulty: float, cfg: FlatTerrainWithTrashBinCfg +) -> tuple[list[trimesh.Trimesh], np.ndarray]: + + mesh_list = [] + + # ------------------------- + # Ground: square plane centered at (0, 0) + # ------------------------- + ground = trimesh.creation.box( + extents=(cfg.size[0], cfg.size[1], 0.10), + transform=trimesh.transformations.translation_matrix((0.0, 0.0, -0.005)), + ) + mesh_list.append(ground) + + # ------------------------- + # Trash bin (relative to terrain center) + # ------------------------- + bin_x = cfg.trash_bin_x + bin_y = cfg.trash_bin_y if hasattr(cfg, "trash_bin_y") else 0.0 + + bin_diameter = 2.0 + bin_radius = 0.5 * bin_diameter + bin_height = 0.5 + wall_thickness = 0.02 + bottom_thickness = 0.05 + + bin_color = np.asarray([255, 128, 0, 255], dtype=np.uint8) + + # Bottom: solid circular plate. + bottom = trimesh.creation.cylinder( + radius=bin_radius, + height=bottom_thickness, + transform=trimesh.transformations.translation_matrix((bin_x, bin_y, bottom_thickness / 2)), + ) + bottom.visual.vertex_colors = np.tile(bin_color, (bottom.vertices.shape[0], 1)) + mesh_list.append(bottom) + + # Wall: annulus ring as circular bin wall. + wall = trimesh.creation.annulus( + r_min=max(0.0, bin_radius - wall_thickness), + r_max=bin_radius, + height=bin_height, + transform=trimesh.transformations.translation_matrix((bin_x, bin_y, bottom_thickness + bin_height / 2)), + ) + wall.visual.vertex_colors = np.tile(bin_color, (wall.vertices.shape[0], 1)) + mesh_list.append(wall) + + # ------------------------- + # Robot spawn origin: terrain center + # ------------------------- + origin = np.array([0.0, 0.0, 0.0]) + + return mesh_list, origin + + + +@configclass +class FlatTerrainWithTrashBinCfg(SubTerrainBaseCfg): + """Configuration for flat terrain with a trash bin at x=4.5. + + The trash bin is an orange hollow circle with open top. + """ + function = flat_terrain_with_trash_bin + trash_bin_x: float = 7 # Position relative to origin + + +TASK_B_TERRAIN_CFG = TerrainImporterCfg( + class_type=BetterTerrainImporter, + prim_path="/World/ground", + terrain_type="generator", + terrain_generator=TerrainGeneratorCfg( + class_type=BetterTerrainGenerator, + seed=0, + size=(20, 20), + border_width=0.0, + num_rows=1, + num_cols=1, + horizontal_scale=0.1, + vertical_scale=0.005, + slope_threshold=0.75, + use_cache=False, + sub_terrains={ + "flat_with_bin": FlatTerrainWithTrashBinCfg(proportion=1.0), + }, + ), + max_init_terrain_level=0, + collision_group=-1, + physics_material=sim_utils.RigidBodyMaterialCfg( + friction_combine_mode="multiply", + restitution_combine_mode="multiply", + static_friction=1.0, + dynamic_friction=1.0, + restitution=1.0, + ), + visual_material=sim_utils.MdlFileCfg( + mdl_path=f"{ATEC_ASSETS_MODEL_DIR}/scene/TilesMarbleSpiderWhiteBrickBondHoned.mdl", + project_uvw=True, + texture_scale=(0.25, 0.25), + ), + # visual_material=None, + debug_vis=False, +) diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_base/__init__.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_base/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0276f1d32732d3396a040200f915e4976de57d62 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_base/__init__.py @@ -0,0 +1,8 @@ +# Created by skywoodsz on 2026/02/06. + +from .envs_base import BaseRLEnv +from .envs_base_cfg import BaseEnvCfg, BaseSceneCfg, RewardsCfg, TerminationsCfg +from .terrain_base import BetterTerrainGenerator, BetterTerrainImporter, BetterTerrainGeneratorCfg + +__all__ = ["BaseRLEnv", "BetterTerrainGenerator", "BetterTerrainGeneratorCfg", + "BaseEnvCfg", "BaseSceneCfg", "RewardsCfg", "TerminationsCfg"] \ No newline at end of file diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_base/envs_base.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_base/envs_base.py new file mode 100644 index 0000000000000000000000000000000000000000..63a63b6b91adbbeccd700f295433d0fc2996271e --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_base/envs_base.py @@ -0,0 +1,16 @@ +# Created by skywoodsz on 2026/03/03. + +import torch +from isaaclab.envs import ManagerBasedRLEnv + +class BaseRLEnv(ManagerBasedRLEnv): + def step(self, action: torch.Tensor): + elapsed_time = self.episode_length_buf.to(torch.float32) * float(self.step_dt) + + obs, reward, terminated, truncated, info = super().step(action) + + info["Elapsed_Time"] = elapsed_time + info["Step_dt"] = float(self.step_dt) + info["Episode_Length_s"] = float(self.max_episode_length_s) + + return obs, reward, terminated, truncated, info diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_base/envs_base_cfg.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_base/envs_base_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..101961b9c8cd5f86b6c907fcf5af2ed255907dc9 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_base/envs_base_cfg.py @@ -0,0 +1,395 @@ +# Created by skywoodsz on 2026/02/06. +""" +ATEC environment base class, implementing basic I/O. +""" + +import isaaclab.sim as sim_utils +from dataclasses import MISSING +from isaaclab.assets import ArticulationCfg, AssetBaseCfg +from isaaclab.envs import mdp, ManagerBasedRLEnvCfg +from isaaclab.managers import EventTermCfg as EventTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.managers import ObservationTermCfg as ObsTerm +from isaaclab.managers import RewardTermCfg as RewTerm +from isaaclab.managers import SceneEntityCfg +from isaaclab.managers import TerminationTermCfg as DoneTerm +from isaaclab.scene import InteractiveSceneCfg +from isaaclab.sensors import ContactSensorCfg, RayCasterCfg, patterns, CameraCfg +from isaaclab.utils.noise import AdditiveUniformNoiseCfg as Unoise +from isaaclab.utils import configclass + +import atec_rl_lab.tasks.task_base.mdp as atec_mdp +from atec_rl_lab.assets import ATEC_ASSETS_MODEL_DIR +from atec_rl_lab.assets.robots import ATECArticulationCfg +from .terrain_base import TerrainImporterCfg + +@configclass +class BaseSceneCfg(InteractiveSceneCfg): + """Base configuration for the scene.""" + terrain: TerrainImporterCfg = MISSING + robot: ArticulationCfg = ATECArticulationCfg + + # Lights + sky_light = AssetBaseCfg( + prim_path="/World/skyLight", + spawn=sim_utils.DomeLightCfg( + intensity=750.0, + texture_file=f"{ATEC_ASSETS_MODEL_DIR}/scene/kloofendal_43d_clear_puresky_4k.hdr", + ), + ) + + # Sensors + contact_sensor = ContactSensorCfg( + prim_path="{ENV_REGEX_NS}/Robot/.*", + history_length=3, + track_air_time=True, + ) + lidar_sensor = RayCasterCfg( + prim_path="{ENV_REGEX_NS}/Robot/base_link", + update_period=0.1, + pattern_cfg=patterns.LidarPatternCfg( + vertical_fov_range=(-20.0, 20.0), + horizontal_fov_range=(-180.0, 180.0), + horizontal_res=1.0, + channels=16, + ), + max_distance=10.0, + debug_vis=False, + mesh_prim_paths=["/World/ground"], + ) + + head_camera = CameraCfg( + prim_path="{ENV_REGEX_NS}/Robot/head_camera", + update_period = 0.1, + height = 480, + width = 640, + data_types = ["rgb", "depth"], + spawn = sim_utils.PinholeCameraCfg( + focal_length=24.0, + focus_distance=400.0, + horizontal_aperture=20.955, + clipping_range=(0.05, 50.0), + ), + offset = CameraCfg.OffsetCfg( + pos=(0.0, 0.0, 0.0), + rot=(1.0, 0.0, 0.0, 0.0), + ), + ) + + ee_camera = CameraCfg( + prim_path="{ENV_REGEX_NS}/Robot/ee_camera", + update_period=0.1, + height=480, + width=640, + data_types=["rgb", "depth"], + spawn=sim_utils.PinholeCameraCfg( + focal_length=15.0, + horizontal_aperture=20.955, + clipping_range=(0.05, 50.0), + ), + offset=CameraCfg.OffsetCfg( + pos=(0.0, 0.0, 0.0), + rot=(1.0, 0.0, 0.0, 0.0), + ), + ) + + ee_dual_camera = CameraCfg( + prim_path="{ENV_REGEX_NS}/Robot/ee_dual_camera", + update_period=0.1, + height=480, + width=640, + data_types=["rgb", "depth"], + spawn=sim_utils.PinholeCameraCfg( + focal_length=15.0, + horizontal_aperture=20.955, + clipping_range=(0.05, 50.0), + ), + offset=CameraCfg.OffsetCfg( + pos=(0.0, 0.0, 0.0), + rot=(1.0, 0.0, 0.0, 0.0), + ), + ) + +@configclass +class CommandsCfg: + """Command specifications for the MDP.""" + + base_velocity = mdp.UniformVelocityCommandCfg( + asset_name="robot", + resampling_time_range=(10.0, 10.0), + rel_standing_envs=0.02, + rel_heading_envs=1.0, + heading_command=True, + heading_control_stiffness=0.5, + debug_vis=False, + ranges=mdp.UniformVelocityCommandCfg.Ranges( + lin_vel_x=(-1.0, 1.0), + lin_vel_y=(-1.0, 1.0), + ang_vel_z=(-1.0, 1.0), + heading=(-3.14, 3.14), + ), + ) + +@configclass +class ActionsCfg: + """Action specifications for the MDP.""" + # For leg joint + joint_pos_leg = mdp.JointPositionActionCfg( + asset_name="robot", joint_names=[""], scale=0.5, use_default_offset=True, clip=None, preserve_order=True + ) + # For wheel joint + joint_vel_wheel = mdp.JointVelocityActionCfg( + asset_name="robot", joint_names=[""], scale=5.0, use_default_offset=True, clip=None, preserve_order=True + ) + # For manipulator joint + joint_pos_arm = mdp.JointPositionActionCfg( + asset_name="robot", joint_names=[""], scale=0.5, use_default_offset=True, clip=None, preserve_order=True + ) + + +@configclass +class ObservationsCfg: + """Observation specifications for the MDP.""" + + @configclass + class ProprioObservationsCfg(ObsGroup): + """Observations for proprioception group.""" + # observation terms (order preserved) + base_lin_vel = ObsTerm( + func=mdp.base_lin_vel, noise=Unoise(n_min=-0.1, n_max=0.1) + ) + base_ang_vel = ObsTerm( + func=mdp.base_ang_vel, noise=Unoise(n_min=-0.2, n_max=0.2) + ) + velocity_commands = ObsTerm( + func=mdp.generated_commands, + params={"command_name": "base_velocity"}, + clip=(-100.0, 100.0), + scale=1.0, + ) + projected_gravity = ObsTerm( + func=mdp.projected_gravity, + noise=Unoise(n_min=-0.05, n_max=0.05), + ) + joint_pos = ObsTerm( + func=mdp.joint_pos_rel, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=".*", preserve_order=True)}, + noise=Unoise(n_min=-0.01, n_max=0.01) + ) + joint_vel = ObsTerm( + func=mdp.joint_vel_rel, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=".*", preserve_order=True)}, + noise=Unoise(n_min=-1.5, n_max=1.5)) + actions = ObsTerm(func=mdp.last_action) + + def __post_init__(self): + self.enable_corruption = False + self.concatenate_terms = True + + @configclass + class ExteroObservationsCfg(ObsGroup): + """Observations for exteroception group.""" + + # observation terms (order preserved) + lidar_scan = ObsTerm( + func=mdp.height_scan, params={"sensor_cfg": SceneEntityCfg("lidar_sensor")} + ) + + def __post_init__(self): + self.enable_corruption = False + self.concatenate_terms = True + + @configclass + class ImageObservationsCfg(ObsGroup): + """Observations for image group.""" + + # observation terms (order preserved) + head_rgb = ObsTerm( + func=mdp.image, + params={"sensor_cfg": SceneEntityCfg("head_camera"), "data_type": "rgb", "normalize": False,}, + ) + head_depth = ObsTerm( + func=mdp.image, + params={"sensor_cfg": SceneEntityCfg("head_camera"), "data_type": "depth"}, + ) + + ee_rgb = ObsTerm( + func=mdp.image, + params={"sensor_cfg": SceneEntityCfg("ee_camera"), "data_type": "rgb", "normalize": False,}, + ) + ee_depth = ObsTerm( + func=mdp.image, + params={"sensor_cfg": SceneEntityCfg("ee_camera"), "data_type": "depth"}, + ) + + ee_dual_rgb = ObsTerm( + func=mdp.image, + params={"sensor_cfg": SceneEntityCfg("ee_dual_camera"), "data_type": "rgb", "normalize": False,}, + ) + ee_dual_depth = ObsTerm( + func=mdp.image, + params={"sensor_cfg": SceneEntityCfg("ee_dual_camera"), "data_type": "depth"}, + ) + + def __post_init__(self): + self.enable_corruption = False + self.concatenate_terms = False + + # observation groups + proprio: ProprioObservationsCfg = ProprioObservationsCfg() + extero: ExteroObservationsCfg = ExteroObservationsCfg() + image: ImageObservationsCfg = ImageObservationsCfg() + +@configclass +class EventCfg: + """Configuration for events.""" + # startup + physics_material = EventTerm( + func=mdp.randomize_rigid_body_material, + mode="startup", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names=".*"), + "static_friction_range": (0.8, 0.8), + "dynamic_friction_range": (0.6, 0.6), + "restitution_range": (0.0, 0.0), + "num_buckets": 64, + }, + ) + + # reset + base_external_force_torque = EventTerm( + func=mdp.apply_external_force_torque, + mode="reset", + params={ + "asset_cfg": SceneEntityCfg("robot", body_names="base.*"), + "force_range": (0.0, 0.0), + "torque_range": (-0.0, 0.0), + }, + ) + + reset_robot_joints = EventTerm( + func=mdp.reset_joints_by_scale, + mode="reset", + params={ + "position_range": (0.5, 1.5), + "velocity_range": (0.0, 0.0), + }, + ) + +@configclass +class RewardsCfg: + """Reward terms for the MDP.""" + # elapsed_time = RewTerm(func=atec_mdp.elapsed_time, weight=1) + distance_from_origin = RewTerm( + func=atec_mdp.distance_from_origin, + params={"asset_cfg": SceneEntityCfg("robot")}, + weight=1, + ) + + +@configclass +class TerminationsCfg: + """Termination terms for the MDP.""" + + time_out = DoneTerm(func=mdp.time_out, time_out=True) + illegal_contact = DoneTerm( + func=mdp.illegal_contact, + params={ + "sensor_cfg": SceneEntityCfg("contact_sensor", body_names="base.*"), + "threshold": 1.0, + }, + ) + fall = DoneTerm( + func=mdp.root_height_below_minimum, + params={ + "asset_cfg": SceneEntityCfg("robot"), + "minimum_height": 0.0, + }, + time_out=False, + ) + # bad_orientation = DoneTerm( + # func=mdp.bad_orientation, + # params={ + # "asset_cfg": SceneEntityCfg("robot"), + # "limit_angle": 0.7 + # }, + # time_out=False, + # ) + +class BaseEnvCfg(ManagerBasedRLEnvCfg): + """Base environment configuration.""" + + # Scene settings + scene: BaseSceneCfg = BaseSceneCfg(num_envs=4096, env_spacing=2.5) + # Basic settings + actions: ActionsCfg = ActionsCfg() + observations: ObservationsCfg = ObservationsCfg() + # MDP settings + events: EventCfg = EventCfg() + rewards: RewardsCfg = RewardsCfg() + terminations: TerminationsCfg = TerminationsCfg() + commands: CommandsCfg = CommandsCfg() + + def __post_init__(self): + """Post initialization.""" + # general settings + self.decimation = 4 + self.episode_length_s = 1200 # 20 min + # simulation settings + self.sim.dt = 0.005 + self.sim.render_interval = self.decimation + self.sim.physx.gpu_max_rigid_patch_count = 10 * 2**15 + # sensor feedback settings + self.scene.contact_sensor.update_period = self.sim.dt * self.decimation + + robot_cfg = self.scene.robot + base_path = "{ENV_REGEX_NS}/Robot" + + lidar_sensor_link_name = getattr(robot_cfg, "lidar_sensor_link_name", None) + if isinstance(lidar_sensor_link_name, str): + self.scene.lidar_sensor.prim_path = base_path + "/" + lidar_sensor_link_name + else: + self.scene.lidar_sensor = None + self.observations.extero.lidar_scan = None + + head_camera_link_name = getattr(robot_cfg, "head_camera_link_name", None) + head_camera_offset = getattr(robot_cfg, "head_camera_offset", None) + if isinstance(head_camera_link_name, str): + self.scene.head_camera.prim_path = base_path + "/" + head_camera_link_name + "/head_camera" + if head_camera_offset is not None: + self.scene.head_camera.offset = head_camera_offset + else: + self.scene.head_camera = None + self.observations.image.head_rgb = None + self.observations.image.head_depth = None + + ee_camera_link_name = getattr(robot_cfg, "ee_camera_link_name", None) + ee_camera_offset = getattr(robot_cfg, "ee_camera_offset", None) + if isinstance(ee_camera_link_name, str): + self.scene.ee_camera.prim_path = base_path + "/" + ee_camera_link_name + "/ee_camera" + if ee_camera_offset is not None: + self.scene.ee_camera.offset = ee_camera_offset[0] if isinstance(ee_camera_offset, tuple) else ee_camera_offset + self.scene.ee_dual_camera = None + self.observations.image.ee_dual_rgb = None + self.observations.image.ee_dual_depth = None + elif isinstance(ee_camera_link_name, tuple): + self.scene.ee_camera.prim_path = base_path + "/" + ee_camera_link_name[0] + "/ee_camera" + self.scene.ee_dual_camera.prim_path = base_path + "/" + ee_camera_link_name[1] + "/ee_dual_camera" + if ee_camera_offset is not None: + if isinstance(ee_camera_offset, tuple): + # Allow independent offsets for left/right EE cameras. + self.scene.ee_camera.offset = ee_camera_offset[0] + self.scene.ee_dual_camera.offset = ee_camera_offset[1] + else: + self.scene.ee_camera.offset = ee_camera_offset + self.scene.ee_dual_camera.offset = ee_camera_offset + else: + self.scene.ee_camera = None + self.observations.image.ee_rgb = None + self.observations.image.ee_depth = None + + self.scene.ee_dual_camera = None + self.observations.image.ee_dual_rgb = None + self.observations.image.ee_dual_depth = None + + self.terminations.illegal_contact.params["sensor_cfg"].body_names = getattr(robot_cfg, "base_link_name", "base.*") diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_base/mdp/__init__.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_base/mdp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..861f6d8fd0c3624c9842bba5d9b986fa61ae04ef --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_base/mdp/__init__.py @@ -0,0 +1,3 @@ +# Created by skywoodsz on 2026/02/07. + +from .rewards import * diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_base/mdp/rewards.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_base/mdp/rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..bfe6bbce0c7415391c1b93dee1c3bf67175de8d7 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_base/mdp/rewards.py @@ -0,0 +1,43 @@ +# Created by skywoodsz on 2026/02/07. + +""" +ATEC scoring criteria +""" + +from __future__ import annotations + +import torch +from typing import TYPE_CHECKING + + +from isaaclab.assets import Articulation, RigidObject +from isaaclab.managers import SceneEntityCfg + + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +def elapsed_time(env: ManagerBasedRLEnv) -> torch.Tensor: + """ + Return current elapsed episode time (seconds) for each env. + + Shape: (num_envs,) + """ + t = env.common_step_counter * env.step_dt + + return torch.full( (env.num_envs,), float(t), device=env.device, dtype=torch.float32) + + +def distance_from_origin(env: ManagerBasedRLEnv, asset_cfg: SceneEntityCfg = SceneEntityCfg("robot")) -> torch.Tensor: + """ + Return distance from world origin for each env. + + Args: + asset_cfg: Scene entity config for the asset whose root position is used. + + Shape: (num_envs,) + """ + asset: Articulation | RigidObject = env.scene[asset_cfg.name] + root_pos_w = asset.data.root_pos_w + return torch.linalg.norm(root_pos_w, dim=-1) \ No newline at end of file diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_base/terrain_base.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_base/terrain_base.py new file mode 100644 index 0000000000000000000000000000000000000000..292b6b30ccca309dac5903cd2f6bd2f16d5ec239 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_base/terrain_base.py @@ -0,0 +1,170 @@ +# Created by skywoodsz on 2026/02/06. +# copy from btx0424 +from __future__ import annotations + +import trimesh +import numpy as np +from isaaclab.terrains import ( + SubTerrainBaseCfg, + TerrainImporterCfg, + TerrainImporter, + TerrainGenerator, +) +import isaaclab.sim as sim_utils +from isaaclab.utils import configclass +from isaaclab.terrains import TerrainImporterCfg, TerrainGeneratorCfg +from isaaclab.sim.spawners.spawner_cfg import SpawnerCfg +from isaaclab.sim.spawners.from_files import spawn_ground_plane +from isaaclab.sim.spawners import materials + +from atec_rl_lab.assets import ATEC_ASSETS_MODEL_DIR + +class BetterTerrainImporter(TerrainImporter): + def __init__(self, cfg: TerrainImporterCfg): + """Initialize the terrain importer. Different from IsaacLab's TerrainImporter, + this class holds the terrain generator object. + + Args: + cfg: The configuration for the terrain importer. + + Raises: + ValueError: If input terrain type is not supported. + ValueError: If terrain type is 'generator' and no configuration provided for ``terrain_generator``. + ValueError: If terrain type is 'usd' and no configuration provided for ``usd_path``. + ValueError: If terrain type is 'usd' or 'plane' and no configuration provided for ``env_spacing``. + """ + # check that the config is valid + cfg.validate() + # store inputs + self.cfg = cfg + self.device = sim_utils.SimulationContext.instance().device # type: ignore + + # create buffers for the terrains + self.terrain_prim_paths = list() + self.terrain_origins = None + self.env_origins = None # assigned later when `configure_env_origins` is called + # private variables + self._terrain_flat_patches = dict() + + # auto-import the terrain based on the config + self.terrain_generator = None + if self.cfg.terrain_type == "generator": + # check config is provided + if self.cfg.terrain_generator is None: + raise ValueError("Input terrain type is 'generator' but no value provided for 'terrain_generator'.") + # generate the terrain + terrain_generator = self.cfg.terrain_generator.class_type( + cfg=self.cfg.terrain_generator, device=self.device + ) + self.import_mesh("terrain", terrain_generator.terrain_mesh) + # configure the terrain origins based on the terrain generator + self.configure_env_origins(terrain_generator.terrain_origins) + # refer to the flat patches + self._terrain_flat_patches = terrain_generator.flat_patches + self.terrain_generator = terrain_generator + elif self.cfg.terrain_type == "usd": + # check if config is provided + if self.cfg.usd_path is None: + raise ValueError("Input terrain type is 'usd' but no value provided for 'usd_path'.") + # import the terrain + self.import_usd("terrain", self.cfg.usd_path) + # configure the origins in a grid + self.configure_env_origins() + elif self.cfg.terrain_type == "plane": + # load the plane + self.import_ground_plane("terrain") + # configure the origins in a grid + self.configure_env_origins() + else: + raise ValueError(f"Terrain type '{self.cfg.terrain_type}' not available.") + + # set initial state of debug visualization + self.set_debug_vis(self.cfg.debug_vis) + + def import_ground_plane(self, name: str, size: tuple[float, float] = (2.0e6, 2.0e6)): + """Add a plane to the terrain importer. + + Args: + name: The name of the imported terrain. This name is used to create the USD prim + corresponding to the terrain. + size: The size of the plane. Defaults to (2.0e6, 2.0e6). + + Raises: + ValueError: If a terrain with the same name already exists. + """ + # create prim path for the terrain + prim_path = self.cfg.prim_path + f"/{name}" + # check if key exists + if prim_path in self.terrain_prim_paths: + raise ValueError( + f"A terrain with the name '{name}' already exists. Existing terrains: {', '.join(self.terrain_names)}." + ) + # store the mesh name + self.terrain_prim_paths.append(prim_path) + + # obtain ground plane color from the configured visual material + color = (0.0, 0.0, 0.0) + if self.cfg.visual_material is not None: + material = self.cfg.visual_material.to_dict() + # defaults to the `GroundPlaneCfg` color if diffuse color attribute is not found + if "diffuse_color" in material: + color = material["diffuse_color"] + else: + logger.warning( + "Visual material specified for ground plane but no diffuse color found." + " Using default color: (0.0, 0.0, 0.0)" + ) + + # get the mesh + ground_plane_cfg = GroundPlaneCfg(physics_material=self.cfg.physics_material, size=size, color=color) + ground_plane_cfg.func(prim_path, ground_plane_cfg) + +@configclass +class GroundPlaneCfg(SpawnerCfg): + """Create a ground plane prim. + + This uses the USD for the standard grid-world ground plane from Isaac Sim by default. + """ + + func: Callable = spawn_ground_plane + + usd_path: str = f"{ATEC_ASSETS_MODEL_DIR}/scene/plane/default_environment.usd" + """Path to the USD file to spawn asset from. Defaults to the grid-world ground plane.""" + + color: tuple[float, float, float] | None = (0.0, 0.0, 0.0) + """The color of the ground plane. Defaults to (0.0, 0.0, 0.0). + + If None, then the color remains unchanged. + """ + + size: tuple[float, float] = (100.0, 100.0) + """The size of the ground plane. Defaults to 100 m x 100 m.""" + + physics_material: materials.RigidBodyMaterialCfg = materials.RigidBodyMaterialCfg() + """Physics material properties. Defaults to the default rigid body material.""" + +@configclass +class BetterTerrainGeneratorCfg(TerrainGeneratorCfg): + terrain_sequence: list[str] | None = None + +class BetterTerrainGenerator(TerrainGenerator): + sub_terrain_types = [] + _cell_counter = 0 + + def _get_terrain_mesh( + self, difficulty: float, cfg: SubTerrainBaseCfg + ) -> tuple[trimesh.Trimesh, np.ndarray]: + + seq = getattr(self.cfg, "terrain_sequence", None) + if seq is not None: + key = seq[self._cell_counter % len(seq)] + if key not in self.cfg.sub_terrains: + raise KeyError( + f"terrain_sequence key '{key}' not in cfg.sub_terrains: {list(self.cfg.sub_terrains.keys())}") + cfg = self.cfg.sub_terrains[key] + else: + key = [k for k, v in self.cfg.sub_terrains.items() if v == cfg][0] + + self._cell_counter += 1 + self.sub_terrain_types.append(key) + return super()._get_terrain_mesh(difficulty, cfg) \ No newline at end of file diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_d/__init__.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_d/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b2b725338eeda9d5ce84d2229b88041ef7e33296 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_d/__init__.py @@ -0,0 +1,61 @@ +import gymnasium as gym + +from .terrain import TASK_D_TERRAIN_CFG +from .env_cfg import TaskDEnvCfg, TaskDEnvB2Cfg, TaskDEnvTron2ALeggedCfg, TaskDEnvTron2AWheelCfg + + +gym.register( + id = "ATEC-TaskD-G1", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskDEnvG1Cfg" + }, +) + +gym.register( + id = "ATEC-TaskD-Tron1Piper", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskDEnvTron1Cfg" + }, +) + +gym.register( + id = "ATEC-TaskD-Tron2ALegged", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskDEnvTron2ALeggedCfg" + }, +) + +gym.register( + id = "ATEC-TaskD-Tron2AWheel", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskDEnvTron2AWheelCfg" + }, +) + +gym.register( + id = "ATEC-TaskD-B2Piper", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskDEnvB2Cfg" + }, +) + +gym.register( + id = "ATEC-TaskD-B2wPiper", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskDEnvB2WCfg" + }, +) + +__all__ = ['TaskDEnvCfg', 'TaskDEnvB2Cfg', 'TaskDEnvTron2ALeggedCfg', 'TaskDEnvTron2AWheelCfg'] diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_d/env_cfg.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_d/env_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..310c5c754607007acebb3cb4eccdea4b8a437427 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_d/env_cfg.py @@ -0,0 +1,310 @@ +# Created by skywoodsz on 2026/02/06. + +""" +Implementation of Task D environment configuration with different robots. +""" + +import copy +from isaaclab.utils import configclass +import atec_rl_lab.tasks.task_d.mdp as atec_mdp +from isaaclab.managers import RewardTermCfg as RewTerm +from isaaclab.managers import TerminationTermCfg as DoneTerm +from isaaclab.managers import SceneEntityCfg +from isaaclab.assets import RigidObjectCfg +from isaaclab.sensors import MultiMeshRayCasterCfg +import isaaclab.sim as sim_utils + +from atec_rl_lab.tasks.task_base import BaseEnvCfg +from atec_rl_lab.tasks.task_base.envs_base_cfg import TerminationsCfg as BaseTerminationsCfg +from .terrain import TASK_D_TERRAIN_CFG, PitAndPlatformTerrainCfg + +@configclass +class RewardsCfg: + """Reward terms for the MDP.""" + achieve = RewTerm( + func=atec_mdp.RewardCrossX, + params={"asset_cfg": SceneEntityCfg("robot"), + "threshold": [-1.4, 2.0], + "reward_value": [2, 20.0], + "debug": False, + "visual_assets": True, + }, + weight=1.0, + ) + box_in_target_x = RewTerm( + func=atec_mdp.RewardBoxXInRange, + params={ + "asset_cfg": SceneEntityCfg("box"), + "x_min": [-0.7, -1.4], + "x_max": [0.7, -0.7], + "reward_value": 14.0, + "one_time": True, + "debug": False, + }, + weight=1.0, + ) + +@configclass +class TaskDTerminationsCfg(BaseTerminationsCfg): + x_reached = DoneTerm( + func=atec_mdp.robot_x_greater_than, + params={ + "asset_cfg": SceneEntityCfg("robot"), + "x_threshold": 3.5, + }, + time_out=False, + ) + +@configclass +class TaskDEnvCfg(BaseEnvCfg): + pit_width_range: tuple[float, float] = (1.3, 1.4) + platform_height_range: tuple[float, float] = (1.0, 1.2) + + def _build_terrain_cfg(self): + terrain_cfg = copy.deepcopy(TASK_D_TERRAIN_CFG) + pit_cfg = terrain_cfg.terrain_generator.sub_terrains.get("pit_and_platform") + if isinstance(pit_cfg, PitAndPlatformTerrainCfg): + pit_cfg.pit_width_range = self.pit_width_range + pit_cfg.platform_height_range = self.platform_height_range + return terrain_cfg + + def __post_init__(self): + super().__post_init__() + + self.scene.terrain = self._build_terrain_cfg() + self.scene.box = RigidObjectCfg( + prim_path="{ENV_REGEX_NS}/Box", + spawn=sim_utils.CuboidCfg( + size=(0.8, 1.0, 0.6), + rigid_props=sim_utils.RigidBodyPropertiesCfg( + disable_gravity=False, + ), + collision_props=sim_utils.CollisionPropertiesCfg( + collision_enabled=True, + ), + mass_props=sim_utils.MassPropertiesCfg(mass=8.0), + physics_material=sim_utils.RigidBodyMaterialCfg( + static_friction=0.9, + dynamic_friction=0.8, + restitution=0.0, + ), + ), + init_state=RigidObjectCfg.InitialStateCfg( + pos=(-3, 1.6, 0.5), # -3, 1.6, 0.5 + ), + ) + self.sim.physics_material = self.scene.terrain.physics_material + + if self.scene.lidar_sensor is not None: + lidar_sensor = self.scene.lidar_sensor + self.scene.lidar_sensor = MultiMeshRayCasterCfg( + prim_path=lidar_sensor.prim_path, + update_period=lidar_sensor.update_period, + pattern_cfg=lidar_sensor.pattern_cfg, + max_distance=lidar_sensor.max_distance, + debug_vis=lidar_sensor.debug_vis, + offset=lidar_sensor.offset, + attach_yaw_only=lidar_sensor.attach_yaw_only, + ray_alignment=lidar_sensor.ray_alignment, + drift_range=lidar_sensor.drift_range, + ray_cast_drift_range=lidar_sensor.ray_cast_drift_range, + visualizer_cfg=lidar_sensor.visualizer_cfg, + mesh_prim_paths=[ + "/World/ground", + MultiMeshRayCasterCfg.RaycastTargetCfg( + prim_expr="{ENV_REGEX_NS}/Box", + is_shared=True, + track_mesh_transforms=True, + ), + ], + ) + + # Task D reward + self.rewards = RewardsCfg() + self.terminations = TaskDTerminationsCfg() + + # Turn off the DR and noise + self.observations.proprio.enable_corruption = False + self.observations.extero.enable_corruption = False + self.events.physics_material = None + self.events.base_external_force_torque = None + + # Trun off terminations + self.terminations.illegal_contact = None + self.terminations.fall.params["minimum_height"] = 0.25 + +@configclass +class TaskDEnvG1Cfg(TaskDEnvCfg): + """Environment configuration for Task C with Unitree g1.""" + + pit_width_range: tuple[float, float] = (0.9, 1.0) + platform_height_range: tuple[float, float] = (0.9, 1.0) + + def __post_init__(self): + from atec_rl_lab.assets.robots import UNITREE_G1_29DOF_DEX1_CFG + + self.scene.robot = UNITREE_G1_29DOF_DEX1_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state = UNITREE_G1_29DOF_DEX1_CFG.init_state.replace( + pos=(-3, 0.0, 0.8), + ) + ) + super().__post_init__() + + # self.terminations.illegal_contact.params["sensor_cfg"].body_names = [ + # UNITREE_G1_29DOF_DEX1_CFG.base_link_name, + # ".*_hip_(pitch|roll|yaw)_link" + # ] + + joint_names = UNITREE_G1_29DOF_DEX1_CFG.joint_names + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + self.actions.joint_pos_leg.joint_names = joint_names + self.actions.joint_vel_wheel = None + self.actions.joint_pos_arm = None + + +@configclass +class TaskDEnvTron1Cfg(TaskDEnvCfg): + def __post_init__(self): + from atec_rl_lab.assets.robots import TRON1A_PIPER_CFG + + self.scene.robot = TRON1A_PIPER_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state = TRON1A_PIPER_CFG.init_state.replace( + pos=(-3, 0.0, 0.8 + 0.166), + ) + ) + super().__post_init__() + + # self.terminations.illegal_contact.params["sensor_cfg"].body_names = [ + # TRON1A_PIPER_CFG.base_link_name, + # "abad_[LR]_Link", + # ] + + joint_names = TRON1A_PIPER_CFG.joint_names + leg_joint_names = TRON1A_PIPER_CFG.leg_joint_names + wheel_joint_names = TRON1A_PIPER_CFG.wheel_joint_names + arm_joint_names = TRON1A_PIPER_CFG.arm_joint_names + + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + + self.actions.joint_pos_leg.joint_names = leg_joint_names + self.actions.joint_vel_wheel.joint_names = wheel_joint_names + self.actions.joint_pos_arm.joint_names = arm_joint_names + + +@configclass +class TaskDEnvTron2ALeggedCfg(TaskDEnvCfg): + def __post_init__(self): + from atec_rl_lab.assets.robots import TRON2A_LEGGED_CFG + + self.scene.robot = TRON2A_LEGGED_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=TRON2A_LEGGED_CFG.init_state.replace( + pos=(-3, 0.0, 0.8 + 0.166), + ) + ) + super().__post_init__() + + joint_names = TRON2A_LEGGED_CFG.joint_names + leg_joint_names = TRON2A_LEGGED_CFG.leg_joint_names + arm_joint_names = TRON2A_LEGGED_CFG.arm_joint_names + + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + + self.actions.joint_pos_leg.joint_names = leg_joint_names + self.actions.joint_vel_wheel = None + self.actions.joint_pos_arm.joint_names = arm_joint_names + + +@configclass +class TaskDEnvTron2AWheelCfg(TaskDEnvCfg): + def __post_init__(self): + from atec_rl_lab.assets.robots import TRON2A_WHEEL_CFG + + self.scene.robot = TRON2A_WHEEL_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=TRON2A_WHEEL_CFG.init_state.replace( + pos=(-3, 0.0, 0.8 + 0.166), + ) + ) + super().__post_init__() + + joint_names = TRON2A_WHEEL_CFG.joint_names + leg_joint_names = TRON2A_WHEEL_CFG.leg_joint_names + wheel_joint_names = TRON2A_WHEEL_CFG.wheel_joint_names + arm_joint_names = TRON2A_WHEEL_CFG.arm_joint_names + + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + + self.actions.joint_pos_leg.joint_names = leg_joint_names + self.actions.joint_vel_wheel.joint_names = wheel_joint_names + self.actions.joint_pos_arm.joint_names = arm_joint_names + + +@configclass +class TaskDEnvB2Cfg(TaskDEnvCfg): + def __post_init__(self): + from atec_rl_lab.assets.robots import UNITREE_B2_PIPER_CFG + + self.scene.robot = UNITREE_B2_PIPER_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=UNITREE_B2_PIPER_CFG.init_state.replace( + pos=(-3, 0.0, 0.8), + ) + ) + + super().__post_init__() + + # self.terminations.illegal_contact.params["sensor_cfg"].body_names = [ + # UNITREE_B2_PIPER_CFG.base_link_name, + # ".*_hip", + # ".*_thigh", + # ] + + joint_names = UNITREE_B2_PIPER_CFG.joint_names + leg_joint_names = UNITREE_B2_PIPER_CFG.leg_joint_names + arm_joint_names = UNITREE_B2_PIPER_CFG.arm_joint_names + + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + + self.actions.joint_pos_leg.joint_names = leg_joint_names + self.actions.joint_pos_arm.joint_names = arm_joint_names + self.actions.joint_vel_wheel = None + + +@configclass +class TaskDEnvB2WCfg(TaskDEnvCfg): + def __post_init__(self): + from atec_rl_lab.assets.robots import UNITREE_B2W_PIPER_CFG + + self.scene.robot = UNITREE_B2W_PIPER_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state = UNITREE_B2W_PIPER_CFG.init_state.replace( + pos=(-3, 0.0, 0.78), + ) + ) + super().__post_init__() + + # self.terminations.illegal_contact.params["sensor_cfg"].body_names = [ + # UNITREE_B2W_PIPER_CFG.base_link_name, + # ".*_hip", + # ".*_thigh", + # ] + + joint_names = UNITREE_B2W_PIPER_CFG.joint_names + leg_joint_names = UNITREE_B2W_PIPER_CFG.leg_joint_names + wheel_joint_names = UNITREE_B2W_PIPER_CFG.wheel_joint_names + arm_joint_names = UNITREE_B2W_PIPER_CFG.arm_joint_names + + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + + self.actions.joint_pos_leg.joint_names = leg_joint_names + self.actions.joint_vel_wheel.joint_names = wheel_joint_names + self.actions.joint_pos_arm.joint_names = arm_joint_names diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_d/mdp/__init__.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_d/mdp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..63302ef807566270a8e685a37efba74bd8947f93 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_d/mdp/__init__.py @@ -0,0 +1,2 @@ +from .rewards import * +from .terminations import * diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_d/mdp/rewards.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_d/mdp/rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..0bf87092dbde9f61a3dc56efb04e9e784855d358 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_d/mdp/rewards.py @@ -0,0 +1,352 @@ +from __future__ import annotations + +import torch +from typing import TYPE_CHECKING, Sequence + +import isaaclab.sim as sim_utils +from isaaclab.managers.manager_base import ManagerTermBase + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +class RewardCrossX(ManagerTermBase): + """One-time reward when robot crosses x threshold(s). + """ + + def __init__(self, cfg, env): + super().__init__(cfg, env) + + self._initialized = False + self._reward_given = None + + # visual assets + self._visual_spawned = False + self._visual_prim_paths = [] + self._last_visual_update_step = -1 + + def _init_buffers(self, num_thresholds: int = 1): + if self._initialized: + return + + self._reward_given = torch.zeros( + (self._env.num_envs, num_thresholds), + dtype=torch.bool, + device=self._env.device, + ) + self._initialized = True + + def _set_prim_color(self, prim_path: str, color: tuple[float, float, float]): + """Set display color of a spawned cuboid prim.""" + try: + import omni.usd + from pxr import UsdGeom, Vt + + stage = omni.usd.get_context().get_stage() + prim = stage.GetPrimAtPath(prim_path) + if not prim.IsValid(): + return + + gprim = UsdGeom.Gprim(prim) + gprim.CreateDisplayColorAttr() + gprim.GetDisplayColorAttr().Set(Vt.Vec3fArray([color])) + except Exception as e: + print(f"[RewardCrossX] Failed to set color for {prim_path}: {e}") + + def _spawn_threshold_assets_once( + self, + thresholds: Sequence[float], + parent_prim_path: str = "/World/Visuals/RewardCrossX", + line_length_y: float = 10.0, + line_thickness_x: float = 0.02, + line_height_z: float = 0.25, + color_default: tuple[float, float, float] = (1.0, 0.2, 0.2), + ): + """Spawn one thin cuboid line for each threshold in each env. + """ + if self._visual_spawned: + return + + try: + import omni.usd + from pxr import UsdGeom + + stage = omni.usd.get_context().get_stage() + if not stage.GetPrimAtPath(parent_prim_path).IsValid(): + UsdGeom.Xform.Define(stage, parent_prim_path) + except Exception: + pass + + self._visual_prim_paths = [] + + for env_id in range(self._env.num_envs): + env_paths = [] + for th_idx, th in enumerate(thresholds): + prim_path = f"{parent_prim_path}/env_{env_id}_threshold_{th_idx}" + + cfg = sim_utils.CuboidCfg( + size=(line_thickness_x, line_length_y, line_height_z), + visual_material=None, + collision_props=None, + rigid_props=None, + mass_props=None, + ) + + cfg.func( + prim_path=prim_path, + cfg=cfg, + translation=( + float(th), + 0.0, + float(3.0 + line_height_z * 0.5), + ), + ) + + self._set_prim_color(prim_path, color_default) + env_paths.append(prim_path) + + self._visual_prim_paths.append(env_paths) + + self._visual_spawned = True + + def _update_threshold_asset_colors( + self, + color_default: tuple[float, float, float] = (1.0, 0.2, 0.2), + color_triggered: tuple[float, float, float] = (0.2, 1.0, 0.2), + ): + """Update line color based on per-threshold reward status.""" + if not self._visual_spawned: + return + + for env_id, env_paths in enumerate(self._visual_prim_paths): + for th_idx, prim_path in enumerate(env_paths): + color = color_triggered if self._reward_given[env_id, th_idx] else color_default + self._set_prim_color(prim_path, color) + + def reset(self, env_ids=None): + if not self._initialized: + return + + if env_ids is None: + self._reward_given.fill_(False) + else: + self._reward_given[env_ids] = False + + if self._visual_spawned: + self._update_threshold_asset_colors() + + def _normalize_threshold_reward_params( + self, + thresholds: Sequence[float] | None, + reward_values: Sequence[float] | None, + threshold: float | Sequence[float], + reward_value: float | Sequence[float], + threshold_2: float | None, + reward_value_2: float, + ) -> tuple[list[float], list[float]]: + """Normalize scalar/list args into float lists. + """ + + def _is_sequence(v) -> bool: + return isinstance(v, Sequence) and not isinstance(v, (str, bytes)) + + if thresholds is not None or reward_values is not None: + if thresholds is None or reward_values is None: + raise ValueError("thresholds and reward_values must be provided together.") + thresholds_list = [float(x) for x in thresholds] + reward_values_list = [float(x) for x in reward_values] + if _is_sequence(threshold) or _is_sequence(reward_value) or threshold_2 is not None: + raise ValueError( + "Do not mix thresholds/reward_values with threshold/reward_value/threshold_2." + ) + else: + th_is_seq = _is_sequence(threshold) + rew_is_seq = _is_sequence(reward_value) + if th_is_seq != rew_is_seq: + raise ValueError( + "threshold and reward_value must both be scalar or both be list." + ) + + if th_is_seq: + if threshold_2 is not None: + raise ValueError("threshold_2 cannot be used when threshold is a list.") + thresholds_list = [float(x) for x in threshold] + reward_values_list = [float(x) for x in reward_value] + else: + thresholds_list = [float(threshold)] + reward_values_list = [float(reward_value)] + if threshold_2 is not None: + thresholds_list.append(float(threshold_2)) + reward_values_list.append(float(reward_value_2)) + + if len(thresholds_list) == 0: + raise ValueError("At least one threshold is required.") + if len(thresholds_list) != len(reward_values_list): + raise ValueError( + "thresholds and reward_values must have same length, " + f"got {len(thresholds_list)} and {len(reward_values_list)}." + ) + for i in range(1, len(thresholds_list)): + if thresholds_list[i] <= thresholds_list[i - 1]: + raise ValueError("thresholds must be strictly increasing.") + + return thresholds_list, reward_values_list + + def __call__( + self, + env: ManagerBasedRLEnv, + asset_cfg, + threshold: float | Sequence[float] = 0.6, + reward_value: float | Sequence[float] = 24.0, + threshold_2: float | None = None, + reward_value_2: float = 0.0, + thresholds: Sequence[float] | None = None, + reward_values: Sequence[float] | None = None, + debug: bool = False, + visual_assets: bool = False, + visual_update_interval: int = 10, + parent_prim_path: str = "/World/Visuals/RewardCrossX", + line_length_y: float = 10.0, + line_thickness_x: float = 0.02, + line_height_z: float = 0.5, + ) -> torch.Tensor: + thresholds, reward_values = self._normalize_threshold_reward_params( + thresholds=thresholds, + reward_values=reward_values, + threshold=threshold, + reward_value=reward_value, + threshold_2=threshold_2, + reward_value_2=reward_value_2, + ) + + num_thresholds = len(thresholds) + + if not self._initialized: + self._init_buffers(num_thresholds=num_thresholds) + elif self._reward_given.shape[1] != num_thresholds: + raise ValueError( + "RewardCrossX threshold count changed after initialization. " + f"Expected {self._reward_given.shape[1]}, got {num_thresholds}." + ) + + if visual_assets and not self._visual_spawned: + self._spawn_threshold_assets_once( + thresholds=thresholds, + parent_prim_path=parent_prim_path, + line_length_y=line_length_y, + line_thickness_x=line_thickness_x, + line_height_z=line_height_z, + ) + elif visual_assets and self._visual_spawned and self._visual_prim_paths: + if len(self._visual_prim_paths[0]) != num_thresholds: + raise ValueError( + "RewardCrossX visual threshold count changed after spawn. " + f"Expected {len(self._visual_prim_paths[0])}, got {num_thresholds}." + ) + + robot = env.scene[asset_cfg.name] + + root_pos_x = robot.data.root_pos_w[:, 0] + thresholds_t = torch.tensor(thresholds, device=root_pos_x.device, dtype=root_pos_x.dtype) + reward_values_t = torch.tensor(reward_values, device=root_pos_x.device, dtype=root_pos_x.dtype) + + crossed = root_pos_x.unsqueeze(1) > thresholds_t.unsqueeze(0) + trigger = crossed & (~self._reward_given) + self._reward_given |= crossed + + reward = (trigger.float() * reward_values_t.unsqueeze(0)).sum(dim=1) + + if debug: + print( + f"[RewardCrossX] x={root_pos_x[0].item():.3f}, " + f"crossed={crossed[0].tolist()}, " + f"trigger={trigger[0].tolist()}, " + f"reward={reward[0].item():.3f}" + ) + + if visual_assets and self._visual_spawned: + step = getattr(env, "common_step_counter", 0) + if step != self._last_visual_update_step and step % visual_update_interval == 0: + self._update_threshold_asset_colors() + self._last_visual_update_step = step + + return reward + + +class RewardBoxXInRange(ManagerTermBase): + """Give reward when the target box x-position is within one or more x-ranges.""" + + def __init__(self, cfg, env): + super().__init__(cfg, env) + self._reward_given = torch.zeros(self._env.num_envs, dtype=torch.bool, device=self._env.device) + + def reset(self, env_ids=None): + if env_ids is None: + self._reward_given.fill_(False) + else: + self._reward_given[env_ids] = False + + def _normalize_ranges( + self, + x_min: float | Sequence[float], + x_max: float | Sequence[float], + ) -> tuple[list[float], list[float]]: + is_min_seq = isinstance(x_min, Sequence) and not isinstance(x_min, (str, bytes)) + is_max_seq = isinstance(x_max, Sequence) and not isinstance(x_max, (str, bytes)) + + if is_min_seq != is_max_seq: + raise ValueError("x_min and x_max must both be scalar or both be sequences.") + + if is_min_seq: + x_min_list = [float(v) for v in x_min] + x_max_list = [float(v) for v in x_max] + if len(x_min_list) == 0: + raise ValueError("At least one x-range is required.") + if len(x_min_list) != len(x_max_list): + raise ValueError("x_min and x_max sequences must have the same length.") + else: + x_min_list = [float(x_min)] + x_max_list = [float(x_max)] + + for mn, mx in zip(x_min_list, x_max_list): + if mn > mx: + raise ValueError(f"Invalid x-range: x_min ({mn}) must be <= x_max ({mx}).") + + return x_min_list, x_max_list + + def __call__( + self, + env: ManagerBasedRLEnv, + asset_cfg, + x_min: float | Sequence[float] = -1.0, + x_max: float | Sequence[float] = 1.0, + reward_value: float = 14.0, + one_time: bool = True, + debug: bool = False, + ) -> torch.Tensor: + box = env.scene[asset_cfg.name] + box_x = box.data.root_pos_w[:, 0] + + x_min_list, x_max_list = self._normalize_ranges(x_min=x_min, x_max=x_max) + + in_any_range = torch.zeros_like(box_x, dtype=torch.bool) + for mn, mx in zip(x_min_list, x_max_list): + in_any_range |= (box_x >= mn) & (box_x <= mx) + + if one_time: + trigger = in_any_range & (~self._reward_given) + self._reward_given |= in_any_range + reward = trigger.to(box_x.dtype) * float(reward_value) + else: + reward = in_any_range.to(box_x.dtype) * float(reward_value) + + if debug: + print( + f"[RewardBoxXInRange] box_x={box_x[0].item():.3f}, " + f"in_any_range={bool(in_any_range[0].item())}, " + f"ranges={list(zip(x_min_list, x_max_list))}, " + f"reward={reward[0].item():.3f}" + ) + + return reward + diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_d/mdp/terminations.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_d/mdp/terminations.py new file mode 100644 index 0000000000000000000000000000000000000000..30dd2e68fe9b3448ce73c7279297076116178aae --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_d/mdp/terminations.py @@ -0,0 +1,21 @@ +# Created by skywoodsz on 4/4/26. + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +from isaaclab.managers import SceneEntityCfg + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnv + + +def robot_x_greater_than( + env: ManagerBasedRLEnv, + asset_cfg: SceneEntityCfg = SceneEntityCfg("robot"), + x_threshold: float = 2.0, +) -> torch.Tensor: + """Terminate when robot root x (world frame) is greater than threshold.""" + robot = env.scene[asset_cfg.name] + return robot.data.root_pos_w[:, 0] > float(x_threshold) diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_d/terrain.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_d/terrain.py new file mode 100644 index 0000000000000000000000000000000000000000..6d7527ff9925e97113a337e31ff5a1643cd7fce1 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_d/terrain.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +import trimesh +import numpy as np +import random +import isaaclab.sim as sim_utils +from isaaclab.terrains import ( + SubTerrainBaseCfg, + TerrainGeneratorCfg, + TerrainImporterCfg, + MeshPlaneTerrainCfg +) +from isaaclab.terrains.trimesh.utils import make_border +from isaaclab.utils import configclass + +from atec_rl_lab.assets import ATEC_ASSETS_MODEL_DIR +from atec_rl_lab.tasks.task_base import BetterTerrainGenerator, BetterTerrainImporter + + +def pit_and_platform_terrain( + difficulty: float, cfg: PitAndPlatformTerrainCfg +) -> tuple[list[trimesh.Trimesh], np.ndarray]: + """Generate a terrain with a pit and an adjacent platform. + + The terrain contains a pit of fixed depth (0.4 m) with a bottom surface, and a platform + positioned randomly on either the left or right side of the pit. The pit width and platform + height are scaled linearly with the difficulty parameter based on their respective ranges + in the configuration. The platform width matches the pit width, creating a choice for the + robot to either traverse the pit or use the elevated platform to bypass it. + + Args: + difficulty: Difficulty parameter in [0, 1] that scales the pit width and platform height + between their configured minimum and maximum values. + cfg: Configuration object containing terrain parameters such as size, pit width range, + platform height range, and border width. + + Returns: + A tuple containing: + - A list of trimesh.Trimesh objects representing the terrain meshes (pit borders, + pit bottom, and platform). + - A numpy array of shape (3,) representing the origin position where the robot + should be spawned, located at 25% along the x-axis and centered on the y-axis. + """ + mesh_list = [] + pit_depth = cfg.pit_depth + pit_width = cfg.pit_width_range[0] + difficulty * ( + cfg.pit_width_range[1] - cfg.pit_width_range[0] + ) + platform_width = pit_width + platform_height = cfg.platform_height_range[0] + difficulty * ( + cfg.platform_height_range[1] - cfg.platform_height_range[0] + ) + mesh_list.extend( + make_border( + size=(cfg.size[0], cfg.size[1] - cfg.border_width), + inner_size=(pit_width, cfg.size[1] - cfg.border_width - 0.2), + height=pit_depth, + position=(cfg.size[0] / 2, cfg.size[1] / 2, -pit_depth / 2), + ) + ) + pit_bottom_thickness = 0.2 + pit_bottom = trimesh.creation.box( + extents=(pit_width, cfg.size[1] - cfg.border_width, pit_bottom_thickness), + transform=trimesh.transformations.translation_matrix( + (cfg.size[0] / 2, cfg.size[1] / 2, -pit_depth - pit_bottom_thickness / 2) + ), + ) + # left_or_right = random.choice([0.25, 0.75]) + left_or_right = 0.75 + platform = trimesh.creation.box( + extents=(platform_width, cfg.size[1] / 2 - cfg.border_width, platform_height), + transform=trimesh.transformations.translation_matrix( + (cfg.size[0] / 2, cfg.size[1] * left_or_right, platform_height / 2) + ), + ) + mesh_list.append(pit_bottom) + mesh_list.append(platform) + origin = np.array([cfg.size[0] * 0.15, cfg.size[1] / 2, 0.0]) + return mesh_list, origin + + +@configclass +class PitAndPlatformTerrainCfg(SubTerrainBaseCfg): + """Configuration for a terrain with a pit and an adjacent platform. + + This terrain type creates a navigation challenge where a robot must choose between + traversing a pit or using an elevated platform positioned randomly on either the left + or right side of the pit. The pit width and platform height are scaled by the difficulty + parameter within their specified ranges. + + Attributes: + border_width: Width of the border around the terrain (in m). Defaults to 0.5. + pit_width_range: Minimum and maximum width of the pit (in m). The actual width + is interpolated based on difficulty. Defaults to (0.8, 1.2). + platform_height_range: Minimum and maximum height of the platform above ground + (in m). The actual height is interpolated based on difficulty. Defaults to (0.3, 0.6). + """ + + function = pit_and_platform_terrain + border_width: float = 1.0 + pit_depth: float = 1.0 + # wo random + pit_width_range: tuple[float, float] = (1.6, 1.7) + platform_height_range: tuple[float, float] = (1.4, 1.5) + + +def platform_terrain(difficulty: float, cfg: PlatformTerrainCfg) -> tuple[list[trimesh.Trimesh], np.ndarray]: + platform_width = cfg.platform_width_range[0] + random.random() * ( + cfg.platform_width_range[1] - cfg.platform_width_range[0] + ) + platform_height = cfg.platform_height_range[0] + difficulty * ( + cfg.platform_height_range[1] - cfg.platform_height_range[0] + ) + mesh_list = [] + + ground = trimesh.creation.box( + extents=(cfg.size[0], cfg.size[1], 0.1), + transform=trimesh.transformations.translation_matrix((cfg.size[0] / 2, cfg.size[1] / 2, -0.05)) + ) + mesh_list.append(ground) + + platform = trimesh.creation.box( + extents=(platform_width, cfg.size[1], platform_height), + transform=trimesh.transformations.translation_matrix((cfg.size[0] / 2, cfg.size[1] / 2, platform_height / 2)) + ) + + mesh_list.append(platform) + origin = np.array([cfg.size[0] * 0.15, cfg.size[1] / 2, platform_height]) + return mesh_list, origin + + +@configclass +class PlatformTerrainCfg(SubTerrainBaseCfg): + function = platform_terrain + platform_width_range: tuple[float, float] = (1.9, 2.0) + platform_height_range: tuple[float, float] = (0.5, 0.6) + + +TASK_D_TERRAIN_CFG = TerrainImporterCfg( + class_type=BetterTerrainImporter, + prim_path="/World/ground", + terrain_type="generator", + terrain_generator=TerrainGeneratorCfg( + class_type=BetterTerrainGenerator, + seed=0, + size=(12.0, 8.0), + border_width=0.0, + num_rows=1, + num_cols=1, + horizontal_scale=0.1, + vertical_scale=0.005, + slope_threshold=0.75, + use_cache=False, + sub_terrains={ + "pit_and_platform": PitAndPlatformTerrainCfg(proportion=1.0), + }, + ), + max_init_terrain_level=0, + collision_group=-1, + physics_material=sim_utils.RigidBodyMaterialCfg( + friction_combine_mode="multiply", + restitution_combine_mode="multiply", + static_friction=1.0, + dynamic_friction=1.0, + restitution=1.0, + ), + visual_material=sim_utils.MdlFileCfg( + mdl_path=f"{ATEC_ASSETS_MODEL_DIR}/scene/TilesMarbleSpiderWhiteBrickBondHoned.mdl", + project_uvw=True, + texture_scale=(0.25, 0.25), + ), + debug_vis=False, +) diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_e/__init__.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_e/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b92e8f9a03d145265cbab51f87c86f2a20ae7357 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_e/__init__.py @@ -0,0 +1,14 @@ +import gymnasium as gym + +gym.register( + id="ATEC-TaskE-Piper", + entry_point="atec_rl_lab.tasks.task_base.envs_base:BaseRLEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.env_cfg:TaskEEnvPiperCfg", + }, +) + +from .env_cfg import TaskEEnvPiperCfg + +__all__ = ["TaskEEnvPiperCfg"] diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_e/env_cfg.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_e/env_cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..cba9be8e689254918bcb293e74d0c33c49fd471f --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_e/env_cfg.py @@ -0,0 +1,261 @@ +from isaaclab.utils import configclass +from isaaclab.managers import RewardTermCfg as RewTerm +from isaaclab.managers import ObservationTermCfg as ObsTerm +from isaaclab.managers import ObservationGroupCfg as ObsGroup +from isaaclab.managers import SceneEntityCfg +from isaaclab.managers import TerminationTermCfg as DoneTerm +from isaaclab.envs import mdp +from isaaclab.sensors import CameraCfg +from isaaclab.utils.noise import AdditiveUniformNoiseCfg as Unoise +import isaaclab.sim as sim_utils + +from atec_rl_lab.tasks.task_base import BaseEnvCfg, BaseSceneCfg +from atec_rl_lab.tasks.task_base.envs_base_cfg import ObservationsCfg as BaseObservationsCfg +from atec_rl_lab.tasks.task_base.envs_base_cfg import TerminationsCfg as BaseTerminationsCfg +from atec_rl_lab.assets.objects import Sugar_cfg, Mustard_cfg, Banana_cfg, Table_cfg, Basket_cfg +from atec_rl_lab.tasks.task_e.mdp.terminations import ObjectsInBasketDone +import atec_rl_lab.tasks.task_e.mdp as atec_mdp +from .terrain import TASK_E_TERRAIN_CFG + +TABLE_CENTER_X = 1.00 +TABLE_CENTER_Y = 0.00 +TABLE_CENTER_Z = 0.00 +TABLE_SCALE = 0.01 +TABLE_DIMS_AT_0P008 = (0.6468062441005529, 0.9084968693231588, 0.6613141183247961) +TABLE_DIMS = tuple(dim * (TABLE_SCALE / 0.008) for dim in TABLE_DIMS_AT_0P008) +TABLE_HALF_X = TABLE_DIMS[0] * 0.5 +TABLE_HALF_Y = TABLE_DIMS[1] * 0.5 +TABLE_TOP_Z = TABLE_CENTER_Z + TABLE_DIMS[2] +# Per-object 2-D bounding-box half-extents (world XY, metres, scale=1). +# Must stay in sync with OBJ_HALF_EXTENTS in scripts/act/task_e/config.py. +OBJ_HALF_EXTENTS = { + "object_1": (0.050, 0.044), # Sugar box + "object_2": (0.050, 0.030), # Mustard bottle + "object_3": (0.100, 0.040), # Banana +} +OBJ_BBOX_MARGIN = 0.015 + +BASKET_CENTER_X = TABLE_CENTER_X + 0.08 +BASKET_CENTER_Y = TABLE_CENTER_Y - 0.30 +BASKET_BASE_Z = TABLE_TOP_Z + TABLE_DIMS[2] +BASKET_EXCL_HALF_X = 0.29 +BASKET_EXCL_HALF_Y = 0.32 + +BASKET_SUCCESS_CENTER = (BASKET_CENTER_X, BASKET_CENTER_Y, TABLE_TOP_Z + 0.15) +BASKET_SUCCESS_HALF_X = 0.20 +BASKET_SUCCESS_HALF_Y = 0.11 + +# Task-E global camera used by ACT evaluation/deployment. +CAM_H, CAM_W = 480, 640 +CAM_POS = (TABLE_CENTER_X - 1.2, TABLE_CENTER_Y, TABLE_TOP_Z + 0.8) +CAM_ROT = (0.957, 0.0, 0.290, 0.0) + +@configclass +class TaskERewardsCfg: + objects_in_basket = RewTerm( + func=atec_mdp.ObjectsInBasket, + params={ + "center": BASKET_SUCCESS_CENTER, + "half_x": BASKET_SUCCESS_HALF_X, + "half_y": BASKET_SUCCESS_HALF_Y, + "table_top_z": TABLE_TOP_Z, + }, + weight=3.0, + ) + grasped_objects_once = RewTerm( + func=atec_mdp.GraspedObjectsByEE, + params={ + "ee_body_name": "gripper_base", + "grasp_dist_thresh": 0.20, + "table_top_z": TABLE_TOP_Z, + "min_lift": 0.15, + "reward_per_object": 3.0, + }, + weight=1.0, + ) + +@configclass +class TaskETerminationsCfg(BaseTerminationsCfg): + basket_success = DoneTerm( + func=ObjectsInBasketDone, + params={ + "center": BASKET_SUCCESS_CENTER, + "half_x": BASKET_SUCCESS_HALF_X, + "half_y": BASKET_SUCCESS_HALF_Y, + "table_top_z": TABLE_TOP_Z, + }, + time_out=False, + ) + +@configclass +class TaskEObservationsCfg(BaseObservationsCfg): + """Task-E specific observations overriding BaseEnvCfg defaults.""" + + @configclass + class ProprioObservationsCfg(ObsGroup): + joint_pos = ObsTerm( + func=mdp.joint_pos_rel, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=".*", preserve_order=True)}, + noise=Unoise(n_min=-0.01, n_max=0.01), + ) + joint_vel = ObsTerm( + func=mdp.joint_vel_rel, + params={"asset_cfg": SceneEntityCfg("robot", joint_names=".*", preserve_order=True)}, + noise=Unoise(n_min=-1.5, n_max=1.5), + ) + actions = ObsTerm(func=mdp.last_action) + + def __post_init__(self): + self.enable_corruption = False + self.concatenate_terms = True + + @configclass + class ImageObservationsCfg(ObsGroup): + ee_rgb = ObsTerm( + func=mdp.image, + params={"sensor_cfg": SceneEntityCfg("ee_camera"), "data_type": "rgb", "normalize": False,}, + ) + ee_depth = ObsTerm( + func=mdp.image, + params={"sensor_cfg": SceneEntityCfg("ee_camera"), "data_type": "depth"}, + ) + video_rgb = ObsTerm( + func=mdp.image, + params={"sensor_cfg": SceneEntityCfg("video_cam"), "data_type": "rgb", "normalize": False,}, + ) + video_depth = ObsTerm( + func=mdp.image, + params={"sensor_cfg": SceneEntityCfg("video_cam"), "data_type": "depth"}, + ) + + def __post_init__(self): + self.enable_corruption = False + self.concatenate_terms = False + + proprio: ProprioObservationsCfg = ProprioObservationsCfg() + image: ImageObservationsCfg = ImageObservationsCfg() + +@configclass +class TaskESceneCfg(BaseSceneCfg): + """Scene configuration for tabletop pick-and-place with 3 objects.""" + + table = Table_cfg([TABLE_CENTER_X, TABLE_CENTER_Y, TABLE_CENTER_Z], scale=(TABLE_SCALE, TABLE_SCALE, TABLE_SCALE)) + + object_1 = Sugar_cfg([TABLE_CENTER_X, TABLE_CENTER_Y, TABLE_TOP_Z + 0.03], [0.0, 0.707, 0.0, 0.707], "Object1") + object_2 = Mustard_cfg([TABLE_CENTER_X, TABLE_CENTER_Y, TABLE_TOP_Z + 0.03], [0.0, 0.0, -0.707, 0.707], "Object2") + object_3 = Banana_cfg([TABLE_CENTER_X, TABLE_CENTER_Y, TABLE_TOP_Z + 0.03], [0.0, 0.0, -0.707, 0.707], "Object3") + + basket = Basket_cfg( + [BASKET_CENTER_X, BASKET_CENTER_Y, TABLE_TOP_Z + 0.08], + [0.707, 0, 0, 0.707], + "Basket", + scale=(1.6, 1.6, 1.0), + ) + + video_cam = CameraCfg( + prim_path="{ENV_REGEX_NS}/video_cam", + update_period=0.0, + height=CAM_H, + width=CAM_W, + data_types=["rgb", "depth"], + spawn=sim_utils.PinholeCameraCfg( + focal_length=24.0, + focus_distance=400.0, + horizontal_aperture=20.955, + clipping_range=(0.1, 100.0), + ), + offset=CameraCfg.OffsetCfg(pos=CAM_POS, rot=CAM_ROT, convention="world"), + ) + +class TaskEEnvCfg(BaseEnvCfg): + """Environment configuration for Task E tabletop manipulation.""" + + scene: TaskESceneCfg = TaskESceneCfg(num_envs=512, env_spacing=2.5) + observations: TaskEObservationsCfg = TaskEObservationsCfg() + rewards: TaskERewardsCfg = TaskERewardsCfg() + terminations: TaskETerminationsCfg = TaskETerminationsCfg() + + def __post_init__(self): + super().__post_init__() + + self.scene.terrain = TASK_E_TERRAIN_CFG + self.sim.physics_material = self.scene.terrain.physics_material + + # self.observations.proprio.enable_corruption = False + self.observations.extero = None + # self.observations.image = None + self.events.physics_material = None + self.events.base_external_force_torque = None + self.events.reset_robot_joints = None + + # Per-object Y-bands (must match OBJ_SPAWN_Y_BANDS in scripts/act/task_e/config.py) + x_min, x_max = TABLE_CENTER_X - 0.10, TABLE_CENTER_X + 0.10 + z = TABLE_TOP_Z + 0.05 + y_bands = { + "object_1": (TABLE_CENTER_Y + 0.25, TABLE_CENTER_Y + 0.29), + "object_2": (TABLE_CENTER_Y + 0.14, TABLE_CENTER_Y + 0.20), + "object_3": (TABLE_CENTER_Y + 0.03, TABLE_CENTER_Y + 0.09), + } + import numpy as np + rng = np.random.default_rng(seed=self.seed) + placed: dict[str, tuple[float, float]] = {} + for object_name, (y_min, y_max) in y_bands.items(): + hx, hy = OBJ_HALF_EXTENTS[object_name] + x = y = None + for _ in range(200): + cx = float(rng.uniform(x_min, x_max)) + cy = float(rng.uniform(y_min, y_max)) + ok = all( + abs(cx - px) >= hx + OBJ_HALF_EXTENTS[pn][0] + OBJ_BBOX_MARGIN or + abs(cy - py) >= hy + OBJ_HALF_EXTENTS[pn][1] + OBJ_BBOX_MARGIN + for pn, (px, py) in placed.items() + ) + if ok: + x, y = cx, cy + break + if x is None: # fallback: band centre + x = (x_min + x_max) / 2.0 + y = (y_min + y_max) / 2.0 + placed[object_name] = (x, y) + getattr(self.scene, object_name).init_state.pos = (x, y, z) + +@configclass +class TaskEEnvPiperCfg(TaskEEnvCfg): + def __post_init__(self): + from atec_rl_lab.assets.robots import PIPER_CFG + + piper_cfg = PIPER_CFG.replace( + prim_path="{ENV_REGEX_NS}/Robot", + init_state=PIPER_CFG.init_state.replace( + pos=(TABLE_CENTER_X + TABLE_HALF_X, TABLE_CENTER_Y, TABLE_TOP_Z), + ), + ) + piper_cfg.spawn.rigid_props.disable_gravity = True + piper_cfg = piper_cfg.replace( + init_state=piper_cfg.init_state.replace( + joint_pos={ + "joint1": 0.0, + "joint2": 1.2, # pre-lifts arm above table + "joint3": -1.5, + "joint4": 0.0, + "joint5": 1.2, + "joint6": 0.0, + "joint7": 0.035, # gripper open + "joint8": -0.035, + }, + ) + ) + self.scene.robot = piper_cfg + super().__post_init__() + + self.commands.base_velocity = None + self.terminations.base_contact = None + + self.observations.proprio.velocity_commands = None + + joint_names = PIPER_CFG.joint_names + self.observations.proprio.joint_pos.params["asset_cfg"].joint_names = joint_names + self.observations.proprio.joint_vel.params["asset_cfg"].joint_names = joint_names + self.actions.joint_pos_leg = None + self.actions.joint_vel_wheel = None + self.actions.joint_pos_arm.joint_names = joint_names diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_e/mdp/__init__.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_e/mdp/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..63302ef807566270a8e685a37efba74bd8947f93 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_e/mdp/__init__.py @@ -0,0 +1,2 @@ +from .rewards import * +from .terminations import * diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_e/mdp/rewards.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_e/mdp/rewards.py new file mode 100644 index 0000000000000000000000000000000000000000..091525820c2fe6a23202bd32426ba9a768b33ade --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_e/mdp/rewards.py @@ -0,0 +1,122 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +from isaaclab.managers import RewardTermCfg +from isaaclab.managers.manager_base import ManagerTermBase + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + + +class ObjectsInBasket(ManagerTermBase): + """Count Task E objects that enter the basket area for the first time. + + Reward is one-time per object per episode, so each object contributes at most +1. + """ + + def __init__(self, cfg: RewardTermCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + self._object_names = ("object_1", "object_2", "object_3") + self._counted = torch.zeros( + (self._env.num_envs, len(self._object_names)), + device=self._env.device, + dtype=torch.bool, + ) + + def reset(self, env_ids=None): + if env_ids is None: + self._counted.fill_(False) + else: + self._counted[env_ids] = False + + def __call__( + self, + env: ManagerBasedEnv, + center: tuple[float, float, float] = (1.08, -0.30, 0.74), + half_x: float = 0.20, + half_y: float = 0.11, + table_top_z: float = 0.8266, + ) -> torch.Tensor: + center_xy = torch.tensor(center[:2], device=env.device, dtype=torch.float32) + env_origins_xy = env.scene.env_origins[:, :2] + min_z = float(table_top_z) + max_z = float(table_top_z) + 0.15 + + inside_flags: list[torch.Tensor] = [] + for object_name in self._object_names: + obj = env.scene[object_name] + # Convert world coordinates to per-env local frame before region check. + obj_pos = obj.data.root_pos_w[:, :3] - env.scene.env_origins + inside_x = torch.abs(obj_pos[:, 0] - center_xy[0]) <= half_x + inside_y = torch.abs(obj_pos[:, 1] - center_xy[1]) <= half_y + inside_z = (obj_pos[:, 2] >= min_z) & (obj_pos[:, 2] <= max_z) + inside_flags.append(inside_x & inside_y & inside_z) + + inside = torch.stack(inside_flags, dim=1) + newly_inside = inside & (~self._counted) + self._counted |= inside + + return newly_inside.sum(dim=1).to(torch.float32) + + +class GraspedObjectsByEE(ManagerTermBase): + """Give one-time reward per object when EE (gripper base) grasps it.""" + + def __init__(self, cfg: RewardTermCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + self._object_names = ("object_1", "object_2", "object_3") + self._counted = torch.zeros( + (self._env.num_envs, len(self._object_names)), + device=self._env.device, + dtype=torch.bool, + ) + self._ee_body_idx = None + + def reset(self, env_ids=None): + if env_ids is None: + self._counted.fill_(False) + else: + self._counted[env_ids] = False + + def _ensure_ee_body_idx(self, env: ManagerBasedEnv, ee_body_name: str): + if self._ee_body_idx is not None: + return + robot = env.scene["robot"] + body_ids, _ = robot.find_bodies(ee_body_name) + if len(body_ids) == 0: + raise ValueError( + f"Cannot find EE body by name regex '{ee_body_name}'." + ) + self._ee_body_idx = int(body_ids[0]) + + def __call__( + self, + env: ManagerBasedEnv, + ee_body_name: str = "gripper_base", + grasp_dist_thresh: float = 0.08, + table_top_z: float = 0.8266, + min_lift: float = 0.01, + reward_per_object: float = 3.0, + ) -> torch.Tensor: + self._ensure_ee_body_idx(env, ee_body_name) + + env_origins = env.scene.env_origins + robot = env.scene["robot"] + ee_pos = robot.data.body_pos_w[:, self._ee_body_idx, :3] - env_origins + + grasped_flags: list[torch.Tensor] = [] + for object_name in self._object_names: + obj = env.scene[object_name] + obj_pos = obj.data.root_pos_w[:, :3] - env_origins + dist = torch.linalg.norm(ee_pos - obj_pos, dim=1) + lifted = obj_pos[:, 2] >= (float(table_top_z) + float(min_lift)) + near = dist <= float(grasp_dist_thresh) + grasped_flags.append(near & lifted) + + grasped = torch.stack(grasped_flags, dim=1) + newly_grasped = grasped & (~self._counted) + self._counted |= grasped + + return newly_grasped.sum(dim=1).to(torch.float32) * float(reward_per_object) diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_e/mdp/terminations.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_e/mdp/terminations.py new file mode 100644 index 0000000000000000000000000000000000000000..0a417221ca6b0599c92f0f8756bf9799498df269 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_e/mdp/terminations.py @@ -0,0 +1,45 @@ +# Created by skywoodsz on 4/4/26. + +from __future__ import annotations + +from typing import TYPE_CHECKING + +import torch +from isaaclab.managers import TerminationTermCfg +from isaaclab.managers.manager_base import ManagerTermBase + +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedEnv + + +class ObjectsInBasketDone(ManagerTermBase): + """Terminate an episode once all Task-E objects are inside the basket region.""" + + def __init__(self, cfg: TerminationTermCfg, env: ManagerBasedEnv): + super().__init__(cfg, env) + self._object_names = ("object_1", "object_2", "object_3") + + def __call__( + self, + env: ManagerBasedEnv, + center: tuple[float, float, float] = (1.08, -0.30, 0.74), + half_x: float = 0.20, + half_y: float = 0.11, + table_top_z: float = 0.8266, + ) -> torch.Tensor: + center_xy = torch.tensor(center[:2], device=env.device, dtype=torch.float32) + env_origins_xy = env.scene.env_origins[:, :2] + min_z = float(table_top_z) + max_z = float(table_top_z) + 0.15 + + inside_flags: list[torch.Tensor] = [] + for object_name in self._object_names: + obj = env.scene[object_name] + obj_pos = obj.data.root_pos_w[:, :3] - env.scene.env_origins + inside_x = torch.abs(obj_pos[:, 0] - center_xy[0]) <= half_x + inside_y = torch.abs(obj_pos[:, 1] - center_xy[1]) <= half_y + inside_z = (obj_pos[:, 2] >= min_z) & (obj_pos[:, 2] <= max_z) + inside_flags.append(inside_x & inside_y & inside_z) + + inside = torch.stack(inside_flags, dim=1) + return inside.all(dim=1) diff --git a/source/atec_rl_lab/atec_rl_lab/tasks/task_e/terrain.py b/source/atec_rl_lab/atec_rl_lab/tasks/task_e/terrain.py new file mode 100644 index 0000000000000000000000000000000000000000..5c28692460cd16150942b6f5ef13a8b15c953d29 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/tasks/task_e/terrain.py @@ -0,0 +1,21 @@ +from isaaclab.terrains import TerrainImporterCfg, TerrainGeneratorCfg +import isaaclab.terrains as terrain_gen +import isaaclab.sim as sim_utils + +from atec_rl_lab.tasks.task_base import BetterTerrainGenerator, BetterTerrainImporter, BetterTerrainGeneratorCfg +from atec_rl_lab.assets import ATEC_ASSETS_MODEL_DIR + +TASK_E_TERRAIN_CFG = TerrainImporterCfg( + class_type=BetterTerrainImporter, + prim_path="/World/ground", + terrain_type="plane", + collision_group=-1, + physics_material=sim_utils.RigidBodyMaterialCfg( + friction_combine_mode="multiply", + restitution_combine_mode="multiply", + static_friction=1.0, + dynamic_friction=1.0, + restitution=0.0, + ), + debug_vis=False, +) \ No newline at end of file diff --git a/source/atec_rl_lab/atec_rl_lab/train/__init__.py b/source/atec_rl_lab/atec_rl_lab/train/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..85880181c2d4505f43f537565202c3f5068b0230 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/train/__init__.py @@ -0,0 +1,2 @@ + +from .locomotion import * diff --git a/source/atec_rl_lab/atec_rl_lab/train/act/__init__.py b/source/atec_rl_lab/atec_rl_lab/train/act/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..316f74720ed2c21495f61fc8e5491e934d68207d --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/train/act/__init__.py @@ -0,0 +1,2 @@ + +from .act import * diff --git a/source/atec_rl_lab/atec_rl_lab/train/act/act/detr/detr_vae.py b/source/atec_rl_lab/atec_rl_lab/train/act/act/detr/detr_vae.py new file mode 100644 index 0000000000000000000000000000000000000000..8404eb48ce3d51a98f0251e201a3ecd6046cdcd6 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/train/act/act/detr/detr_vae.py @@ -0,0 +1,141 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +DETR model and criterion classes. +""" +import torch +from torch import nn +from torch.autograd import Variable +from atec_rl_lab.train.act.act.detr.transformer import build_transformer, TransformerEncoder, TransformerEncoderLayer + +import numpy as np + +import IPython +e = IPython.embed + + +def reparametrize(mu, logvar): + std = logvar.div(2).exp() + eps = Variable(std.data.new(std.size()).normal_()) + return mu + std * eps + + +def get_sinusoid_encoding_table(n_position, d_hid): + def get_position_angle_vec(position): + return [position / np.power(10000, 2 * (hid_j // 2) / d_hid) for hid_j in range(d_hid)] + + sinusoid_table = np.array([get_position_angle_vec(pos_i) for pos_i in range(n_position)]) + sinusoid_table[:, 0::2] = np.sin(sinusoid_table[:, 0::2]) # dim 2i + sinusoid_table[:, 1::2] = np.cos(sinusoid_table[:, 1::2]) # dim 2i+1 + + return torch.FloatTensor(sinusoid_table).unsqueeze(0) + + +class DETRVAE(nn.Module): + """ This is the DETR module that performs object detection """ + def __init__(self, backbones, transformer, encoder, state_dim, action_dim, num_queries): + super().__init__() + self.num_queries = num_queries + self.transformer = transformer + self.encoder = encoder + hidden_dim = transformer.d_model + self.action_head = nn.Linear(hidden_dim, action_dim) + self.query_embed = nn.Embedding(num_queries, hidden_dim) + if backbones is not None: + self.input_proj = nn.Conv2d(backbones[0].num_channels, hidden_dim, kernel_size=1) + self.backbones = nn.ModuleList(backbones) + self.input_proj_robot_state = nn.Linear(state_dim, hidden_dim) + else: + self.input_proj_robot_state = nn.Linear(state_dim, hidden_dim) + self.backbones = None + + # encoder extra parameters + self.latent_dim = 32 # size of latent z + self.cls_embed = nn.Embedding(1, hidden_dim) # extra cls token embedding + self.encoder_state_proj = nn.Linear(state_dim, hidden_dim) # project state to embedding + self.encoder_action_proj = nn.Linear(action_dim, hidden_dim) # project action to embedding + self.latent_proj = nn.Linear(hidden_dim, self.latent_dim*2) # project hidden state to latent std, var + self.register_buffer('pos_table', get_sinusoid_encoding_table(1+1+num_queries, hidden_dim)) # [CLS], state, actions + + # decoder extra parameters + self.latent_out_proj = nn.Linear(self.latent_dim, hidden_dim) # project latent sample to embedding + self.additional_pos_embed = nn.Embedding(2, hidden_dim) # learned position embedding for state and proprio + + def forward(self, obs, actions=None): + is_training = actions is not None + state = obs['state'] if self.backbones is not None else obs + bs = state.shape[0] + + if is_training: + # project CLS token, state sequence, and action sequence to embedding dim + cls_embed = self.cls_embed.weight # (1, hidden_dim) + cls_embed = torch.unsqueeze(cls_embed, axis=0).repeat(bs, 1, 1) # (bs, 1, hidden_dim) + state_embed = self.encoder_state_proj(state) # (bs, hidden_dim) + state_embed = torch.unsqueeze(state_embed, axis=1) # (bs, 1, hidden_dim) + action_embed = self.encoder_action_proj(actions) # (bs, seq, hidden_dim) + # concat them together to form an input to the CVAE encoder + encoder_input = torch.cat([cls_embed, state_embed, action_embed], axis=1) # (bs, seq+2, hidden_dim) + encoder_input = encoder_input.permute(1, 0, 2) # (seq+2, bs, hidden_dim) + # no masking is applied to all parts of the CVAE encoder input + is_pad = torch.full((bs, encoder_input.shape[0]), False).to(state.device) # False: not a padding + # obtain position embedding + pos_embed = self.pos_table.clone().detach() + pos_embed = pos_embed.permute(1, 0, 2) # (seq+2, 1, hidden_dim) + # query CVAE encoder + encoder_output = self.encoder(encoder_input, pos=pos_embed, src_key_padding_mask=is_pad) + encoder_output = encoder_output[0] # take cls output only + latent_info = self.latent_proj(encoder_output) + mu = latent_info[:, :self.latent_dim] + logvar = latent_info[:, self.latent_dim:] + latent_sample = reparametrize(mu, logvar) + latent_input = self.latent_out_proj(latent_sample) + else: + mu = logvar = None + latent_sample = torch.zeros([bs, self.latent_dim], dtype=torch.float32).to(state.device) + latent_input = self.latent_out_proj(latent_sample) + + # CVAE decoder + if self.backbones is not None: + vis_data = obs['rgb'] + if "depth" in obs: + vis_data = torch.cat([vis_data, obs['depth']], dim=2) + num_cams = vis_data.shape[1] + + # Image observation features and position embeddings + all_cam_features = [] + all_cam_pos = [] + for cam_id in range(num_cams): + features, pos = self.backbones[0](vis_data[:, cam_id]) # HARDCODED + features = features[0] # take the last layer feature # (batch, hidden_dim, H, W) + pos = pos[0] # (1, hidden_dim, H, W) + all_cam_features.append(self.input_proj(features)) + all_cam_pos.append(pos) + + # proprioception features (state) + proprio_input = self.input_proj_robot_state(state) + # fold camera dimension into width dimension + src = torch.cat(all_cam_features, axis=3) # (batch, hidden_dim, 4, 8) + pos = torch.cat(all_cam_pos, axis=3) # (batch, hidden_dim, 4, 8) + hs = self.transformer(src, None, self.query_embed.weight, pos, latent_input, proprio_input, self.additional_pos_embed.weight)[0] # (batch, num_queries, hidden_dim) + else: + state = self.input_proj_robot_state(state) + hs = self.transformer(None, None, self.query_embed.weight, None, latent_input, state, self.additional_pos_embed.weight)[0] + + a_hat = self.action_head(hs) + return a_hat, [mu, logvar] + + +def build_encoder(args): + d_model = args.hidden_dim # 256 + dropout = args.dropout # 0.1 + nhead = args.nheads # 8 + dim_feedforward = args.dim_feedforward # 2048 + num_encoder_layers = args.enc_layers # 4 # TODO shared with VAE decoder + normalize_before = args.pre_norm # False + activation = "relu" + + encoder_layer = TransformerEncoderLayer(d_model, nhead, dim_feedforward, + dropout, activation, normalize_before) + encoder_norm = nn.LayerNorm(d_model) if normalize_before else None + encoder = TransformerEncoder(encoder_layer, num_encoder_layers, encoder_norm) + + return encoder \ No newline at end of file diff --git a/source/atec_rl_lab/atec_rl_lab/train/act/act/detr/position_encoding.py b/source/atec_rl_lab/atec_rl_lab/train/act/act/detr/position_encoding.py new file mode 100644 index 0000000000000000000000000000000000000000..3b4e883c05603a2cc3c28afd6c8a04fd76d774fd --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/train/act/act/detr/position_encoding.py @@ -0,0 +1,93 @@ +# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved +""" +Various positional encodings for the transformer. +""" +import math +import torch +from torch import nn + +from atec_rl_lab.train.act.act.utils import NestedTensor + +import IPython +e = IPython.embed + +class PositionEmbeddingSine(nn.Module): + """ + This is a more standard version of the position embedding, very similar to the one + used by the Attention is all you need paper, generalized to work on images. + """ + def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None): + super().__init__() + self.num_pos_feats = num_pos_feats + self.temperature = temperature + self.normalize = normalize + if scale is not None and normalize is False: + raise ValueError("normalize should be True if scale is passed") + if scale is None: + scale = 2 * math.pi + self.scale = scale + + def forward(self, tensor): + x = tensor + # mask = tensor_list.mask + # assert mask is not None + # not_mask = ~mask + + not_mask = torch.ones_like(x[0, [0]]) + y_embed = not_mask.cumsum(1, dtype=torch.float32) + x_embed = not_mask.cumsum(2, dtype=torch.float32) + if self.normalize: + eps = 1e-6 + y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale + x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale + + dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device) + dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats) + + pos_x = x_embed[:, :, :, None] / dim_t + pos_y = y_embed[:, :, :, None] / dim_t + pos_x = torch.stack((pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4).flatten(3) + pos_y = torch.stack((pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4).flatten(3) + pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2) + return pos + + +class PositionEmbeddingLearned(nn.Module): + """ + Absolute pos embedding, learned. + """ + def __init__(self, num_pos_feats=256): + super().__init__() + self.row_embed = nn.Embedding(50, num_pos_feats) + self.col_embed = nn.Embedding(50, num_pos_feats) + self.reset_parameters() + + def reset_parameters(self): + nn.init.uniform_(self.row_embed.weight) + nn.init.uniform_(self.col_embed.weight) + + def forward(self, tensor_list: NestedTensor): + x = tensor_list.tensors + h, w = x.shape[-2:] + i = torch.arange(w, device=x.device) + j = torch.arange(h, device=x.device) + x_emb = self.col_embed(i) + y_emb = self.row_embed(j) + pos = torch.cat([ + x_emb.unsqueeze(0).repeat(h, 1, 1), + y_emb.unsqueeze(1).repeat(1, w, 1), + ], dim=-1).permute(2, 0, 1).unsqueeze(0).repeat(x.shape[0], 1, 1, 1) + return pos + + +def build_position_encoding(args): + N_steps = args.hidden_dim // 2 + if args.position_embedding in ('v2', 'sine'): + # TODO find a better way of exposing other arguments + position_embedding = PositionEmbeddingSine(N_steps, normalize=True) + elif args.position_embedding in ('v3', 'learned'): + position_embedding = PositionEmbeddingLearned(N_steps) + else: + raise ValueError(f"not supported {args.position_embedding}") + + return position_embedding \ No newline at end of file diff --git a/source/atec_rl_lab/atec_rl_lab/train/act/act/utils.py b/source/atec_rl_lab/atec_rl_lab/train/act/act/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9aa4749ac5f4bba9bb6ddf476ac4fa6519ee821a --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/train/act/act/utils.py @@ -0,0 +1,161 @@ +from torch.utils.data.sampler import Sampler +import numpy as np +import torch +import torch.distributed as dist +from torch import Tensor +from h5py import File, Group, Dataset +from typing import Optional + + +class NestedTensor(object): + def __init__(self, tensors, mask: Optional[Tensor]): + self.tensors = tensors + self.mask = mask + + def to(self, device): + # type: (Device) -> NestedTensor # noqa + cast_tensor = self.tensors.to(device) + mask = self.mask + if mask is not None: + assert mask is not None + cast_mask = mask.to(device) + else: + cast_mask = None + return NestedTensor(cast_tensor, cast_mask) + + def decompose(self): + return self.tensors, self.mask + + def __repr__(self): + return str(self.tensors) + +def is_dist_avail_and_initialized(): + if not dist.is_available(): + return False + if not dist.is_initialized(): + return False + return True + +def get_rank(): + if not is_dist_avail_and_initialized(): + return 0 + return dist.get_rank() + +def is_main_process(): + return get_rank() == 0 + + +class IterationBasedBatchSampler(Sampler): + """Wraps a BatchSampler. + Resampling from it until a specified number of iterations have been sampled + References: + https://github.com/facebookresearch/maskrcnn-benchmark/blob/master/maskrcnn_benchmark/data/samplers/iteration_based_batch_sampler.py + """ + + def __init__(self, batch_sampler, num_iterations, start_iter=0): + self.batch_sampler = batch_sampler + self.num_iterations = num_iterations + self.start_iter = start_iter + + def __iter__(self): + iteration = self.start_iter + while iteration < self.num_iterations: + # if the underlying sampler has a set_epoch method, like + # DistributedSampler, used for making each process see + # a different split of the dataset, then set it + if hasattr(self.batch_sampler.sampler, "set_epoch"): + self.batch_sampler.sampler.set_epoch(iteration) + for batch in self.batch_sampler: + yield batch + iteration += 1 + if iteration >= self.num_iterations: + break + + def __len__(self): + return self.num_iterations - self.start_iter + + +def worker_init_fn(worker_id, base_seed=None): + """The function is designed for pytorch multi-process dataloader. + Note that we use the pytorch random generator to generate a base_seed. + Please try to be consistent. + References: + https://pytorch.org/docs/stable/notes/faq.html#dataloader-workers-random-seed + """ + if base_seed is None: + base_seed = torch.IntTensor(1).random_().item() + # print(worker_id, base_seed) + np.random.seed(base_seed + worker_id) + +TARGET_KEY_TO_SOURCE_KEY = { + 'states': 'env_states', + 'observations': 'obs', + 'success': 'success', + 'next_observations': 'obs', + # 'dones': 'dones', + # 'rewards': 'rewards', + 'actions': 'actions', +} +def load_content_from_h5_file(file): + if isinstance(file, (File, Group)): + return {key: load_content_from_h5_file(file[key]) for key in list(file.keys())} + elif isinstance(file, Dataset): + return file[()] + else: + raise NotImplementedError(f"Unspported h5 file type: {type(file)}") + +def load_hdf5(path, ): + print('Loading HDF5 file', path) + file = File(path, 'r') + ret = load_content_from_h5_file(file) + file.close() + print('Loaded') + return ret + +def load_traj_hdf5(path, num_traj=None): + print('Loading HDF5 file', path) + file = File(path, 'r') + keys = list(file.keys()) + if num_traj is not None: + assert num_traj <= len(keys), f"num_traj: {num_traj} > len(keys): {len(keys)}" + keys = sorted(keys, key=lambda x: int(x.split('_')[-1])) + keys = keys[:num_traj] + ret = { + key: load_content_from_h5_file(file[key]) for key in keys + } + file.close() + print('Loaded') + return ret +def load_demo_dataset(path, keys=['observations', 'actions'], num_traj=None, concat=True): + # assert num_traj is None + raw_data = load_traj_hdf5(path, num_traj) + # raw_data has keys like: ['traj_0', 'traj_1', ...] + # raw_data['traj_0'] has keys like: ['actions', 'dones', 'env_states', 'infos', ...] + _traj = raw_data['traj_0'] + for key in keys: + source_key = TARGET_KEY_TO_SOURCE_KEY[key] + assert source_key in _traj, f"key: {source_key} not in traj_0: {_traj.keys()}" + dataset = {} + for target_key in keys: + # if 'next' in target_key: + # raise NotImplementedError('Please carefully deal with the length of trajectory') + source_key = TARGET_KEY_TO_SOURCE_KEY[target_key] + dataset[target_key] = [ raw_data[idx][source_key] for idx in raw_data ] + if isinstance(dataset[target_key][0], np.ndarray) and concat: + if target_key in ['observations', 'states'] and \ + len(dataset[target_key][0]) > len(raw_data['traj_0']['actions']): + dataset[target_key] = np.concatenate([ + t[:-1] for t in dataset[target_key] + ], axis=0) + elif target_key in ['next_observations', 'next_states'] and \ + len(dataset[target_key][0]) > len(raw_data['traj_0']['actions']): + dataset[target_key] = np.concatenate([ + t[1:] for t in dataset[target_key] + ], axis=0) + else: + dataset[target_key] = np.concatenate(dataset[target_key], axis=0) + + print('Load', target_key, dataset[target_key].shape) + else: + print('Load', target_key, len(dataset[target_key]), type(dataset[target_key][0])) + return dataset \ No newline at end of file diff --git a/source/atec_rl_lab/atec_rl_lab/train/locomotion/__init__.py b/source/atec_rl_lab/atec_rl_lab/train/locomotion/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5be8e1ae9eb4799a33488e2f2210aef854649ea7 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/train/locomotion/__init__.py @@ -0,0 +1,3 @@ +"""Locomotion environments for legged robots.""" + +from .velocity import * diff --git a/source/atec_rl_lab/atec_rl_lab/utils/__init__.py b/source/atec_rl_lab/atec_rl_lab/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ef2cd8adc7471116d7c665911b9cac120a0213f4 --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/utils/__init__.py @@ -0,0 +1,3 @@ +from .cartesian_controller import CartesianController + +__all__ = ["CartesianController"] diff --git a/source/atec_rl_lab/atec_rl_lab/utils/cartesian_controller.py b/source/atec_rl_lab/atec_rl_lab/utils/cartesian_controller.py new file mode 100644 index 0000000000000000000000000000000000000000..c97a39627673d0831c077a136f4fd6d7e2cae90e --- /dev/null +++ b/source/atec_rl_lab/atec_rl_lab/utils/cartesian_controller.py @@ -0,0 +1,260 @@ +""" +Cartesian-space IK interface for robot end-effector control. + +Example usage:: + + from atec_rl_lab.utils import CartesianController + + ctrl = CartesianController( + robot=env.scene.articulations["robot"], + ee_body_name="gripper_base", + arm_joint_names=["joint1", "joint2", "joint3", "joint4", "joint5", "joint6"], + num_envs=env.num_envs, + device=env.device, + ) + ctrl.reset() + + # In simulation loop: + arm_jpos_des = ctrl.compute(ee_pos_w, ee_quat_w) # world-frame target + # or + arm_jpos_des = ctrl.compute_base(ee_pos_b, ee_quat_b) # base-frame target +""" + +import torch +from isaaclab.assets import Articulation +from isaaclab.controllers import DifferentialIKController, DifferentialIKControllerCfg +from isaaclab.utils.math import subtract_frame_transforms, quat_inv, matrix_from_quat, quat_rotate_inverse + + +class CartesianController: + """ + Cartesian-space controller for a robot arm. + + Converts desired end-effector poses in world frame to arm joint + position targets using Differential Inverse Kinematics. + Also supports directly consuming base-frame targets via ``compute_base``. + + Parameters + ---------- + robot : Articulation + The robot articulation object from the Isaac Lab scene. + ee_body_name : str + Name of the end-effector body/link (e.g. "gripper_base"). + arm_joint_names : list[str] + Names of the arm joints to control (excludes gripper fingers). + num_envs : int + Number of parallel environments. + device : str + Torch device string, e.g. "cuda:0". + command_type : str + ``"pose"`` — control both position and orientation (default). + ``"position"`` — control position only; orientation floats freely. + Use ``"position"`` when the arm starts far from the desired orientation + or when orientation doesn't need to be constrained. + lambda_val : float + Damping factor for Damped Least Squares IK (default 0.1). + Increase for smoother motion near singularities. + max_joint_delta : float + Maximum joint position change per simulation step (radians). + Limits the IK step size to prevent oscillation. Default 0.05 rad/step + (≈2.5 rad/s at 50 Hz = ~143 deg/s). Set to None to disable clamping. + """ + + def __init__( + self, + robot: Articulation, + ee_body_name: str, + arm_joint_names: list[str], + num_envs: int, + device: str, + command_type: str = "pose", + lambda_val: float = 0.1, + max_joint_delta: float = 0.05, + ): + self.robot = robot + self.device = device + self.command_type = command_type + self.max_joint_delta = max_joint_delta + + # Resolve body and joint indices + body_ids, body_names = robot.find_bodies(ee_body_name) + if len(body_ids) != 1: + raise ValueError( + f"Expected exactly one body matching '{ee_body_name}', " + f"found {len(body_ids)}: {body_names}" + ) + self.ee_idx: int = body_ids[0] + + self.arm_ids, arm_names = robot.find_joints(arm_joint_names) + if len(self.arm_ids) == 0: + raise ValueError( + f"No joints found matching {arm_joint_names}. " + f"Available joints: {robot.joint_names}" + ) + + if robot.is_fixed_base: + # Fixed-base: Jacobian rows are body_idx - 1 (root body excluded) + self._jacobi_body_idx = self.ee_idx - 1 + self._jacobi_joint_ids = list(self.arm_ids) + else: + # Floating-base: root body IS included, joint columns shifted +6 + self._jacobi_body_idx = self.ee_idx + self._jacobi_joint_ids = [i + 6 for i in self.arm_ids] + + # Build IK controller + ik_cfg = DifferentialIKControllerCfg( + command_type=command_type, + use_relative_mode=False, + ik_method="dls", + ik_params={"lambda_val": lambda_val}, + ) + self.ik_ctrl = DifferentialIKController(ik_cfg, num_envs=num_envs, device=device) + + # print( + # f"[CartesianController] ee='{ee_body_name}' (idx={self.ee_idx}), " + # f"arm_joints={arm_names}, fixed_base={robot.is_fixed_base}, " + # f"command_type='{command_type}'" + # ) + + def reset(self, env_ids: torch.Tensor | None = None): + """ + Reset the IK state and seed it from the robot's current EE pose. + + Call this after every ``env.reset()`` to avoid stale IK state. + + Parameters + ---------- + env_ids : torch.Tensor, optional + Indices of environments to reset. If None, resets all. + """ + self.ik_ctrl.reset(env_ids) + + root_pose_w = self.robot.data.root_pose_w + ee_pose_w = self.robot.data.body_pose_w[:, self.ee_idx] + ee_pos_b, ee_quat_b = subtract_frame_transforms( + root_pose_w[:, :3], root_pose_w[:, 3:], + ee_pose_w[:, :3], ee_pose_w[:, 3:], + ) + if self.command_type == "position": + self.ik_ctrl.set_command(ee_pos_b, ee_quat=ee_quat_b) + else: + self.ik_ctrl.set_command(torch.cat([ee_pos_b, ee_quat_b], dim=-1)) + + def compute( + self, + ee_pos_w: torch.Tensor, + ee_quat_w: torch.Tensor | None = None, + ) -> torch.Tensor: + """ + Compute desired arm joint positions from a world-frame EE target. + + Parameters + ---------- + ee_pos_w : torch.Tensor + Desired EE position in world frame, shape (num_envs, 3). + ee_quat_w : torch.Tensor, optional + Desired EE orientation (w, x, y, z) in world frame, + shape (num_envs, 4). Required when command_type="pose"; + ignored when command_type="position". + + Returns + ------- + arm_jpos_des : torch.Tensor + Desired joint positions for the arm joints, + shape (num_envs, n_arm_joints). + """ + root_pose_w = self.robot.data.root_pose_w + + if self.command_type == "position": + ee_pos_des_b = quat_rotate_inverse( + root_pose_w[:, 3:], ee_pos_w - root_pose_w[:, :3] + ) + return self.compute_base(ee_pos_des_b, ee_quat_b=None) + + if ee_quat_w is None: + raise ValueError("ee_quat_w is required when command_type='pose'") + + ee_pos_des_b, ee_quat_des_b = subtract_frame_transforms( + root_pose_w[:, :3], root_pose_w[:, 3:], + ee_pos_w, ee_quat_w, + ) + return self.compute_base(ee_pos_des_b, ee_quat_b=ee_quat_des_b) + + def compute_base( + self, + ee_pos_b: torch.Tensor, + ee_quat_b: torch.Tensor | None = None, + ) -> torch.Tensor: + """Compute desired arm joint positions from a base-frame EE target. + + Parameters + ---------- + ee_pos_b : torch.Tensor + Desired EE position in robot base frame, shape (num_envs, 3). + ee_quat_b : torch.Tensor, optional + Desired EE orientation (w, x, y, z) in robot base frame, + shape (num_envs, 4). Required when command_type="pose"; + ignored when command_type="position". + + Returns + ------- + arm_jpos_des : torch.Tensor + Desired joint positions for the arm joints, + shape (num_envs, n_arm_joints). + """ + root_pose_w = self.robot.data.root_pose_w + + if self.command_type == "position": + ee_pose_w_cur = self.robot.data.body_pose_w[:, self.ee_idx] + _, ee_quat_b_now = subtract_frame_transforms( + root_pose_w[:, :3], root_pose_w[:, 3:], + ee_pose_w_cur[:, :3], ee_pose_w_cur[:, 3:], + ) + self.ik_ctrl.set_command(ee_pos_b, ee_quat=ee_quat_b_now) + else: + if ee_quat_b is None: + raise ValueError("ee_quat_b is required when command_type='pose'") + self.ik_ctrl.set_command(torch.cat([ee_pos_b, ee_quat_b], dim=-1)) + + return self._solve_ik_with_current_state(root_pose_w) + + def _solve_ik_with_current_state(self, root_pose_w: torch.Tensor) -> torch.Tensor: + """Run IK solve from current robot state after command has been set.""" + # Retrieve Jacobian (world frame) and rotate to base frame + jacobian = self.robot.root_physx_view.get_jacobians()[ + :, self._jacobi_body_idx, :, self._jacobi_joint_ids + ] + base_rot_mat = matrix_from_quat(quat_inv(root_pose_w[:, 3:])) + jacobian[:, :3] = torch.bmm(base_rot_mat, jacobian[:, :3]) + jacobian[:, 3:] = torch.bmm(base_rot_mat, jacobian[:, 3:]) + + # Current EE pose in base frame + ee_pose_w_cur = self.robot.data.body_pose_w[:, self.ee_idx] + ee_pos_b_cur, ee_quat_b_cur = subtract_frame_transforms( + root_pose_w[:, :3], root_pose_w[:, 3:], + ee_pose_w_cur[:, :3], ee_pose_w_cur[:, 3:], + ) + + arm_jpos_cur = self.robot.data.joint_pos[:, self.arm_ids] + arm_jpos_des = self.ik_ctrl.compute( + ee_pos_b_cur, ee_quat_b_cur, jacobian, arm_jpos_cur + ) + + # Clamp per-step delta to prevent oscillation from large IK steps + if self.max_joint_delta is not None: + delta = arm_jpos_des - arm_jpos_cur + delta = torch.clamp(delta, -self.max_joint_delta, self.max_joint_delta) + arm_jpos_des = arm_jpos_cur + delta + + return arm_jpos_des + + + @property + def ee_pos_w(self) -> torch.Tensor: + """Current EE position in world frame, shape ``(num_envs, 3)``.""" + return self.robot.data.body_pose_w[:, self.ee_idx, :3] + + @property + def ee_quat_w(self) -> torch.Tensor: + """Current EE orientation (w,x,y,z) in world frame, shape ``(num_envs, 4)``.""" + return self.robot.data.body_pose_w[:, self.ee_idx, 3:] diff --git a/source/atec_rl_lab/config/extension.toml b/source/atec_rl_lab/config/extension.toml new file mode 100644 index 0000000000000000000000000000000000000000..23bb1ddf8e46d3c60f91a937e1449c836f393989 --- /dev/null +++ b/source/atec_rl_lab/config/extension.toml @@ -0,0 +1,35 @@ +[package] + +# Semantic Versioning is used: https://semver.org/ +version = "0.1.0" + +# Description +category = "isaaclab" +readme = "README.md" + +title = "ATEC RL Lab" +author = "CUHK LRL" +maintainer = "CUHK LRL" +description="reinforcement learning environments for ATEC 2026" +repository = "https://github.com/skywoodsz/ATEC2026_Simulation_Challenge" +keywords = ["extension", "template", "isaaclab"] + +[dependencies] +"isaaclab" = {} +"isaaclab_assets" = {} +"isaaclab_mimic" = {} +"isaaclab_rl" = {} +"isaaclab_tasks" = {} +# NOTE: Add additional dependencies here + +[[python.module]] +name = "unitree_rl_lab" + +[isaaclab_settings] +# TODO: Uncomment and list any apt dependencies here. +# If none, leave it commented out. +# apt_deps = ["example_package"] +# TODO: Uncomment and provide path to a ros_ws +# with rosdeps to be installed. If none, +# leave it commented out. +# ros_ws = "path/from/extension_root/to/ros_ws" diff --git a/source/atec_rl_lab/pyproject.toml b/source/atec_rl_lab/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..3acb53bbafcdf74e2cbe06dba4ced4ef64915698 --- /dev/null +++ b/source/atec_rl_lab/pyproject.toml @@ -0,0 +1,25 @@ +[build-system] +requires = ["setuptools", "wheel", "toml"] +build-backend = "setuptools.build_meta" + +[project] +name = "atec_rl_lab" +version = "0.2.1" +description = "Reinforcement Learning Lab for ATEC 2026." +dependencies = [ + "argcomplete", +] +requires-python = ">=3.10" +license = { text = "Apache 2.0" } +authors = [ + { name = "CUHK LRL" } +] +maintainers = [ + { name = "CUHK LRL" } +] +classifiers = [ + "Programming Language :: Python :: 3", + "License :: OSI Approved :: Apache Software License", + "Operating System :: POSIX :: Linux" +] +dynamic = [] diff --git a/source/atec_rl_lab/setup.py b/source/atec_rl_lab/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..42de683df730f81ae73a9afd3b9b2e09713aed63 --- /dev/null +++ b/source/atec_rl_lab/setup.py @@ -0,0 +1,43 @@ +import os +import toml + +from setuptools import setup + +# Obtain the extension data from the extension.toml file +EXTENSION_PATH = os.path.dirname(os.path.realpath(__file__)) +# Read the extension.toml file +EXTENSION_TOML_DATA = toml.load(os.path.join(EXTENSION_PATH, "config", "extension.toml")) + +# Minimum dependencies required prior to installation +INSTALL_REQUIRES = [ + # NOTE: Add dependencies + "psutil", + "torchvision", + "diffusers", + "tensorboard", + "wandb", + "h5py", + "tyro", +] + +# Installation operation +setup( + name="atec_rl_lab", + packages=["atec_rl_lab"], + author=EXTENSION_TOML_DATA["package"]["author"], + maintainer=EXTENSION_TOML_DATA["package"]["maintainer"], + url=EXTENSION_TOML_DATA["package"]["repository"], + version=EXTENSION_TOML_DATA["package"]["version"], + description=EXTENSION_TOML_DATA["package"]["description"], + keywords=EXTENSION_TOML_DATA["package"]["keywords"], + install_requires=INSTALL_REQUIRES, + license="Apache 2.0", + include_package_data=True, + python_requires=">=3.10", + classifiers=[ + "Natural Language :: English", + "Programming Language :: Python :: 3.10", + "Isaac Sim :: 4.5.0", + ], + zip_safe=False, +) diff --git "a/third_party/Agilex-College/isaac_sim/piper_isaac_sim/isaac_sim \345\257\274\345\205\245piper urdf.md" "b/third_party/Agilex-College/isaac_sim/piper_isaac_sim/isaac_sim \345\257\274\345\205\245piper urdf.md" new file mode 100644 index 0000000000000000000000000000000000000000..55f7ec8b01c48c399a5d91de427192077b608059 --- /dev/null +++ "b/third_party/Agilex-College/isaac_sim/piper_isaac_sim/isaac_sim \345\257\274\345\205\245piper urdf.md" @@ -0,0 +1,145 @@ +# Isaac_Sim 导入PiPER URDF + +## 摘要 + +在Isaac Sim中导入piper urdf模型 + +## 标签 + +PiPER机械臂、Isaac Sim + +## 仓库 + +- **导航仓库**: https://github.com/agilexrobotics/Agilex-College +- **项目仓库**: https://github.com/agilexrobotics/piper_isaac_sim.git + +## 环境配置 + +- 操作系统:Ubuntu 24.04 +- ROS版本:ROS2 jazzy +- 显卡:5090 + +### 安装显卡驱动 + +``` +sudo apt update +sudo apt upgrade +sudo add-apt-repository ppa:graphics-drivers/ppa +sudo apt update +sudo ubuntu-drivers autoinstall +#重启 +reboot +``` + +重启之后,可以使用以下命令,验证是否驱动是否安装成功 + +``` +nvidia-smi +``` + +![](img/nvidia-smi.png) + +### 安装isaac sim + +安装方法:https://docs.isaacsim.omniverse.nvidia.com/latest/installation/index.html + +根据链接下载完之后,用以下方法解压 + +``` +cd ~/Downloads +unzip "isaac-sim-standalone-5.1.0-linux-x86_64.zip" -d ~/ +cd isaac-sim-standalone-5.1.0-linux-x86_64/ +./post_install.sh +./isaac-sim.selector.sh +``` + +ROS Bridge Extension选择isaacsim.ros2.bridge;然后点击Start启动 + +![](img/start_isaac.png) + +成功打开后,就可以准备导入urdf模型了 + +> + +## 导入URDF + +### 下载urdf模型 + +下载链接:https://github.com/agilexrobotics/piper_isaac_sim.git + +> 后续会持续更新关于piper系列的urdf文件以及USD + +打开isaac sim后;选择左上角的file->Import ;根据实际路径,选择导入的URDF模型 + +![](img/isaac_sim_1.png) + +![](img/isaac_sim_2.png) + +![](img/isaac_sim_3.png) + +成功导入之后,可以看到机械臂出现在中心位置;可以增加个地面;提高亮度 + +![](img/isaac_sim_4.png) + +点击左边的三角按钮;开始仿真后,会发现夹爪会移动,这是因为导入的urdf中没有定义一些物理参数,需要在isaac sim中设置物理参数 + +![](img/isaac_sim_5.png) + +参数的设置方法如下,点开机械臂的joint1;将Drive->Angular 中的Damping 设置为80,Stiffness设置为400;将每个可移动的关节都设置一下 + +> 该参数仅供参考 + +![](img/isaac_sim_6.png) + + + +设置完成之后,再次开始仿真,机械臂就导入成功了 + +### 增加摄像头 + +在空白处右键,Create->Camera;创建一个新的相机视角 + +![](img/isaac_sim_7.png) + +创建完成之后,需要在Property->Transform调整相机视角;然后在Visual->Visibility,选择invisible;将相机隐藏起来 + +![](img/isaac_sim_8.png) + +在空白处右键,Create->Visual Scripting->Action Graph;创建一个Action Graph,需要将相机的视角通过ROS2发布出来 + +![](img/isaac_sim_9.png) + +Action Graph中的内容如下图 + +![](img/isaac_sim_10.png) + +各个模块之前链接完成之后,需要设置一些参数 + +![](img/isaac_sim_11.png) + +Isaac Create Render Product;camera Prim,需要选择新创建的相机视角 + +![](img/isaac_sim_12.png) + +ROS2 Camera Helper ;其中可以设置相机话题的frame id和topicName + +![](img/isaac_sim_13.png) + +Ctrl+s保存一下USD模型,piper的USD模型就导入完成了。 + + + + + + + + + + + + + + + + + diff --git a/tools/anygrasp/check_anygrasp_env.sh b/tools/anygrasp/check_anygrasp_env.sh new file mode 100644 index 0000000000000000000000000000000000000000..338ca598038b97384e67ebd7726096d648f3e41d --- /dev/null +++ b/tools/anygrasp/check_anygrasp_env.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="/home/ubuntu/Documents/01Proj/13atec/ATEC2026_Simulation_Challenge" +PY="/home/ubuntu/envs/genmanip-isaac5-py311/bin/python" +SSL11="/home/ubuntu/projects/manipdojo2026/micromamba/envs/genmanip-sim/lib/python3.10/site-packages/isaacsim/exts/omni.isaac.ros2_bridge/humble/lib" +SDK="${ROOT}/third_party/anygrasp_sdk" + +export PATH="${ROOT}/tools/anygrasp:${PATH}" +export LD_LIBRARY_PATH="${SSL11}:${LD_LIBRARY_PATH:-}" + +echo "[AnyGrasp] root=${ROOT}" +echo "[AnyGrasp] python=$("${PY}" -c 'import sys; print(sys.executable, sys.version.split()[0])')" +echo "[AnyGrasp] torch=$("${PY}" -c 'import torch; print(torch.__version__, torch.version.cuda, torch.cuda.get_device_name(0) if torch.cuda.is_available() else "NO_CUDA")')" + +echo "[AnyGrasp] SDK files" +test -d "${SDK}" && echo " ok: ${SDK}" || echo " missing: ${SDK}" +test -f "${SDK}/grasp_detection/gsnet.so" && echo " ok: grasp_detection/gsnet.so" || echo " missing: grasp_detection/gsnet.so" +test -f "${SDK}/grasp_detection/lib_cxx.so" && echo " ok: grasp_detection/lib_cxx.so" || echo " missing: grasp_detection/lib_cxx.so" +find "${SDK}/grasp_detection/log" -maxdepth 2 -type f -name 'checkpoint*' -print 2>/dev/null | sed 's/^/ checkpoint: /' || true + +echo "[AnyGrasp] Python deps" +"${PY}" - <<'PY' +import importlib +mods = ["open3d", "graspnetAPI"] +for mod in mods: + try: + m = importlib.import_module(mod) + print(f" ok: {mod} {getattr(m, '__version__', '')}") + except Exception as exc: + print(f" missing/broken: {mod}: {exc}") + +try: + import torch # pointnet2 extension expects torch loaded first + import pointnet2._ext + print(" ok: pointnet2._ext") +except Exception as exc: + print(f" missing/broken: pointnet2._ext: {exc}") + +try: + import MinkowskiEngine + print(f" ok: MinkowskiEngine {getattr(MinkowskiEngine, '__version__', '')}") +except Exception as exc: + print(f" missing/broken: MinkowskiEngine: {exc}") +PY + +echo "[AnyGrasp] License feature id" +(cd "${SDK}/license_registration" && ./license_checker -f) || true + +echo "[AnyGrasp] Note: official licenseCfg.json and checkpoint_detection.tar are still required before detection can run." diff --git a/tools/anygrasp/ifconfig b/tools/anygrasp/ifconfig new file mode 100644 index 0000000000000000000000000000000000000000..db5056189abe0781029f6e6f4dceb5d618515a32 --- /dev/null +++ b/tools/anygrasp/ifconfig @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +set -euo pipefail + +if command -v ip >/dev/null 2>&1; then + ip -br addr | while read -r name state addrs; do + mac="$(cat "/sys/class/net/${name}/address" 2>/dev/null || true)" + echo "${name}: flags=0<${state}>" + if [[ -n "${mac}" ]]; then + echo " ether ${mac}" + fi + if [[ -n "${addrs:-}" ]]; then + for addr in ${addrs}; do + if [[ "${addr}" == *.*/* ]]; then + echo " inet ${addr%%/*}" + elif [[ "${addr}" == *:*/* ]]; then + echo " inet6 ${addr%%/*}" + fi + done + fi + done +else + echo "ifconfig compatibility wrapper requires ip(8)" >&2 + exit 127 +fi diff --git a/tools/anygrasp/install_license_and_checkpoint.sh b/tools/anygrasp/install_license_and_checkpoint.sh new file mode 100644 index 0000000000000000000000000000000000000000..09f47bf245d022dd036b2dd9428308681310d072 --- /dev/null +++ b/tools/anygrasp/install_license_and_checkpoint.sh @@ -0,0 +1,76 @@ +#!/usr/bin/env bash +set -euo pipefail + +usage() { + cat <<'EOF' +Usage: + tools/anygrasp/install_license_and_checkpoint.sh + +Installs AnyGrasp license and detection checkpoint into: + third_party/anygrasp_sdk/grasp_detection/license + third_party/anygrasp_sdk/grasp_tracking/license + third_party/anygrasp_sdk/grasp_detection/log/checkpoint_detection.tar + +The license input can be either: + - the official zip returned by AnyGrasp registration, containing a license/ folder, or + - an already-unzipped license directory containing licenseCfg.json. +EOF +} + +if [[ $# -ne 2 ]]; then + usage >&2 + exit 2 +fi + +ROOT="/home/ubuntu/Documents/01Proj/13atec/ATEC2026_Simulation_Challenge" +LICENSE_IN="$1" +CKPT_IN="$2" +DETECTION="${ROOT}/third_party/anygrasp_sdk/grasp_detection" +TRACKING="${ROOT}/third_party/anygrasp_sdk/grasp_tracking" +TMPDIR="$(mktemp -d)" +trap 'rm -rf "${TMPDIR}"' EXIT + +if [[ ! -e "${LICENSE_IN}" ]]; then + echo "license input not found: ${LICENSE_IN}" >&2 + exit 1 +fi +if [[ ! -f "${CKPT_IN}" ]]; then + echo "checkpoint file not found: ${CKPT_IN}" >&2 + exit 1 +fi + +if [[ -d "${LICENSE_IN}" ]]; then + LICENSE_DIR="${LICENSE_IN}" +else + case "${LICENSE_IN}" in + *.zip) + unzip -q "${LICENSE_IN}" -d "${TMPDIR}" + LICENSE_DIR="$(find "${TMPDIR}" -type f -name licenseCfg.json -printf '%h\n' | head -1)" + ;; + *) + echo "license input must be a directory or .zip file: ${LICENSE_IN}" >&2 + exit 1 + ;; + esac +fi + +if [[ -z "${LICENSE_DIR:-}" || ! -f "${LICENSE_DIR}/licenseCfg.json" ]]; then + echo "licenseCfg.json not found inside license input" >&2 + exit 1 +fi + +mkdir -p "${DETECTION}/log" +rm -rf "${DETECTION}/license" "${TRACKING}/license" +cp -a "${LICENSE_DIR}" "${DETECTION}/license" +cp -a "${LICENSE_DIR}" "${TRACKING}/license" +cp -f "${CKPT_IN}" "${DETECTION}/log/checkpoint_detection.tar" + +echo "Installed AnyGrasp license and checkpoint." +echo "Detection license: ${DETECTION}/license/licenseCfg.json" +echo "Tracking license: ${TRACKING}/license/licenseCfg.json" +echo "Checkpoint: ${DETECTION}/log/checkpoint_detection.tar" + +echo "Checking license state..." +export PATH="${ROOT}/tools/anygrasp:${PATH}" +export LD_LIBRARY_PATH="/home/ubuntu/projects/manipdojo2026/micromamba/envs/genmanip-sim/lib/python3.10/site-packages/isaacsim/exts/omni.isaac.ros2_bridge/humble/lib:${LD_LIBRARY_PATH:-}" +(cd "${ROOT}/third_party/anygrasp_sdk/license_registration" && ./license_checker -c "${DETECTION}/license/licenseCfg.json") diff --git a/tools/anygrasp/pip b/tools/anygrasp/pip new file mode 100644 index 0000000000000000000000000000000000000000..a4a5a273d6f36e975873fc4822d1cc3b3bf7e53b --- /dev/null +++ b/tools/anygrasp/pip @@ -0,0 +1,2 @@ +#!/usr/bin/env bash +exec /home/ubuntu/envs/genmanip-isaac5-py311/bin/python -m pip "$@" diff --git a/tools/anygrasp/run_detection_demo.sh b/tools/anygrasp/run_detection_demo.sh new file mode 100644 index 0000000000000000000000000000000000000000..eb350b3a94af2711f15e71f8f9a4ffe3d9fa1c41 --- /dev/null +++ b/tools/anygrasp/run_detection_demo.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +set -euo pipefail + +ROOT="/home/ubuntu/Documents/01Proj/13atec/ATEC2026_Simulation_Challenge" +PY="/home/ubuntu/envs/genmanip-isaac5-py311/bin/python" +SSL11="/home/ubuntu/projects/manipdojo2026/micromamba/envs/genmanip-sim/lib/python3.10/site-packages/isaacsim/exts/omni.isaac.ros2_bridge/humble/lib" +DETECTION="${ROOT}/third_party/anygrasp_sdk/grasp_detection" + +export PATH="${ROOT}/tools/anygrasp:${PATH}" +export LD_LIBRARY_PATH="${SSL11}:${LD_LIBRARY_PATH:-}" +export OMP_NUM_THREADS="${OMP_NUM_THREADS:-12}" + +test -f "${DETECTION}/license/licenseCfg.json" || { + echo "Missing AnyGrasp license: ${DETECTION}/license/licenseCfg.json" >&2 + exit 1 +} +test -f "${DETECTION}/log/checkpoint_detection.tar" || { + echo "Missing AnyGrasp checkpoint: ${DETECTION}/log/checkpoint_detection.tar" >&2 + exit 1 +} + +cd "${DETECTION}" +exec "${PY}" demo.py --checkpoint_path log/checkpoint_detection.tar --top_down_grasp "$@"